Home > database >  Loop through fields and break
Loop through fields and break

Time:09-25

My file looks looks like this:

1000074493 1D # # # # #
1000098165 1D # # # # #
1000105360 1D # # # # #
1000115763 1D 2D # # # #
1000345208 1D # # # # #
1000470774 1D 2D # 4D # #
1000487544 # # 3D # 5D #
1000499657 1D # # # # #
1000531456 1D # # # # #
1000561333 # # # # 5D #

I want to loop per record through fields 2:NF print if $NF != # and stop reading the line but continue in next line. So the expected result would be:

1000074493 1D
1000098165 1D
1000105360 1D
1000115763 1D
1000345208 1D
1000470774 1D
1000487544 3D
1000499657 1D
1000531456 1D
1000561333 5D

My code is:

awk '{for(i=2; i<=NF; i  ) {if($i != "#" ) print $1,$i }}' $FILE

which gives me:

1000074493 1D
1000098165 1D
1000105360 1D
1000115763 1D
1000115763 1D
1000345208 1D
1000470774 1D
1000470774 2D
1000470774 4D
1000487544 3D 
1000487544 5D
1000499657 1D
1000531456 1D
1000561333 5D

What do I need to change?

CodePudding user response:

Found out finally by myself:

awk '{for(i=2; i<=NF; i  ) {if($i != "#" )  print $1,$i }}' $FILE|awk '$1 != p {print $1,$2}{p=$1}'

if anyone knows how to combine both awk statements in one, it would be appreciated!

CodePudding user response:

the following applied to your file gave me your expected result

awk '{i=2; while ($i == "#") i  ; print $1 " " $i}' $FILE

CodePudding user response:

With awk you can do this:

awk 'gsub(/#/,""){print $1,$2}'  file
1000074493 1D
1000098165 1D
1000105360 1D
1000115763 1D
1000345208 1D
1000470774 1D
1000487544 3D
1000499657 1D
1000531456 1D
1000561333 5D
  • Related