using awk with column value conditions

前端 未结 6 500
甜味超标
甜味超标 2020-11-29 18:10

I\'m learning awk from The AWK Programming Language and I have a problem with one of the examples.

If I wanted to print $3 if $2 is equal to a value (e.g.1

相关标签:
6条回答
  • 2020-11-29 18:58

    If you're looking for a particular string, put quotes around it:

    awk '$1 == "findtext" {print $3}'
    

    Otherwise, awk will assume it's a variable name.

    0 讨论(0)
  • 2020-11-29 18:58

    My awk version is 3.1.5.

    Yes, the input file is space separated, no tabs.

    According to arutaku's answer, here's what I tried that worked:

    awk '$8 ~ "ClNonZ"{ print $3; }' test  
    0.180467091
    0.010615711
    0.492569002
    
    
    $ awk '$8 ~ "ClNonZ" { print $3}' test  
    0.180467091
    0.010615711
    0.492569002
    

    What didn't work(I don't know why and maybe due to my awk version:),

    $awk '$8 ~ "^ClNonZ$"{ print $3; }' test
    $awk '$8 == "ClNonZ" { print $3 }' test
    

    Thank you all for your answers, comments and help!

    0 讨论(0)
  • 2020-11-29 19:02

    Depending on the AWK implementation are you using == is ok or not.

    Have you tried ~?. For example, if you want $1 to be "hello":

    awk '$1 ~ /^hello$/{ print $3; }' <infile>
    

    ^ means $1 start, and $ is $1 end.

    0 讨论(0)
  • 2020-11-29 19:08

    please try this

    echo $VAR | grep ClNonZ | awk '{print $3}';
    

    or

    echo cat filename | grep ClNonZ | awk '{print $3}';
    
    0 讨论(0)
  • 2020-11-29 19:10

    This method uses regexp, it should work:

    awk '$2 ~ /findtext/ {print $3}' <infile>
    
    0 讨论(0)
  • 2020-11-29 19:13

    This is more readable for me

    awk '{if ($2 ~ /findtext/) print $3}' <infile>
    
    0 讨论(0)
提交回复
热议问题