Find the answer to your Linux question:
Results 1 to 5 of 5
Just ran into another question: having this data AA ZKYYG BB QRTBG CC TRFDG DD LHSDF How can I ask awk to print column 1 from all lines before the ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Feb 2013
    Posts
    37

    Another about awk


    Just ran into another question:

    having this data
    AA ZKYYG
    BB QRTBG
    CC TRFDG
    DD LHSDF


    How can I ask awk to print column 1 from all lines before the pattern

    $2 ~ /^LH/

    I am trying this but doesnt work, I guess im being too naif:

    awk '{if ( $2 ~/^LH/ ) print (NR-1)$1}' file.txt
    Last edited by sponge; 05-04-2013 at 11:23 PM.

  2. #2
    Linux Newbie
    Join Date
    Nov 2012
    Posts
    224
    simoply keep the first field into a variable which will be printed if the next line matches.
    you could keep them all into an indexed array, and print the one you want by substracting the number row before the matching line.

  3. #3
    Just Joined!
    Join Date
    May 2011
    Location
    Central FL
    Posts
    91
    If I understand correctly:
    Given
    Code:
    AA ZKYYG
    BB QRTBG
    CC TRFDG
    DD LHSDF
    You want the output to be:
    Code:
    AA
    BB
    CC
    Correct?

    If so:
    Code:
    awk '{ if ( $2 ~ /^LH/ ) { exit }; print $1;  }' file.txt
    But, in case I misunderstood - if you want the output to be:
    Code:
    AA
    BB
    CC
    DD
    Then you move the print first:
    Code:
    awk '{ print $1; if ( $2 ~ /^LH/ ) { exit } }' file.txt

  4. #4
    Just Joined!
    Join Date
    Feb 2013
    Posts
    37
    Yes you were right with the first statement. Thank you!

  5. #5
    Just Joined!
    Join Date
    Feb 2013
    Posts
    37
    One more question:

    how does awk deal with elements in columns from different rows?
    In other words, given:

    AA ZKYYG
    BB QRTBG
    CC TRFDG
    DD LHSDF

    when column 1 in row i matches BB and column 2 in line i+2 matches LH, then print OK.

    Sadly, all I can think of is this, but obviously is not sufficient for this purpose

    awk '{if ( $1 ~ /AA/ && $2 /LH/ print "OK"}'

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •