How can I use awk or grep to select data from different lines?

If I'm in the middle of a script that currently has an input pipe:

text sometext moretext text
othertext more somemore futhertext
text sometext moretext text
othertext more somemore futhertext
etc etc (the 2 patterns repeat)

      

and I want to select, say, a column 2nd

for the first row and a column 4th

for the second row, and then pipe the output so that I finish:

sometext
furthertext

      

Is there a way to do this? I know there are awk '{print $2}'

and awk '{print $4}'

, but how do I get it to select different columns in different rows?

+3


source to share


3 answers


$ awk 'BEGIN{split("2 4",a)} NR in a {print $(a[NR])}' file
sometext
futhertext

      

or if you want it to repeat for EVERY 1st and 2nd line:

$ awk 'BEGIN{n=split("2 4",a)} {print $(a[(NR-1)%n+1])}' file
sometext
futhertext
sometext
futhertext
etc

      



and if you want to do different fields for 3rd and 4th lines, this is trivially extensible:

$ awk 'BEGIN{n=split("2 4 1 3",a)} {print $(a[(NR-1)%n+1])}' file
sometext
futhertext
text
somemore
etc

      

+1


source


awk '{print (NR%2 == 0 ? $4 : $2)}' test.txt

      



It uses triple if to check the line number. ( NR

contains the value of the line number.)

+4


source


If you need a shortcode, this might solve the problem:

awk '{$0=NR%2?$2:$4}1' file

      

0


source







All Articles