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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With