Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk "if" statement

Tags:

awk

I have a file

foo
--
bar

I only want the lines above the separator. I've struggled with this for too long and tried a number of variants. My one liner is:

echo -e "foo\n-- \nbar" | gawk -v x=0 -- '/^--\ / { x++ } ; IF (x==0) {print} '

This should print only "foo" but I get the whole file output. If I change to print x I get

0
1
1

I can't seem to make make awk conditionally print a line based on the value of x. I know I am missing something simple.

like image 740
Grant Bowman Avatar asked Feb 18 '23 07:02

Grant Bowman


1 Answers

Try doing this :

echo -e "foo\n-- \nbar" | awk '/^--/{exit}1'

EXPLANATIONS

  • /^--/ is a regex to match the string at the beginning of the current line
  • {} part is executed if the condition is true (the previous regex)
  • 1 is like {print} : by default, awk print on STDOUT if a condition is true. While 1 is true for awk, it print the current line.

Decomposition of the command :

echo -e "foo\n-- \nbar" | awk '
    {
        if (/^--/) {
            exit
        }
        else {
            print
        }
    }
'

Alternative decomposition:

echo -e "foo\n-- \nbar" |
awk '(/^--/) { exit }
             { print }'

This emphasizes that there are two pattern-action rules; one with an explicit pattern and an exit action; the other with implicit pattern and print action.

like image 149
Gilles Quenot Avatar answered Feb 23 '23 14:02

Gilles Quenot