I'm trying to write an awk
script which checks certain conditions and throws away lines meeting those conditions.
The specific condition are to throw away the first two lines of the file and any line that starts with the text xyzzy:
. To that end, I coded up:
awk ' NR < 2 {} /^xyzzy:/ {} {print}'
thinking that it would throw away the lines where either of those two conditions were met and print otherwise.
Unfortunately, it appears that the print
is being processed even when the line matches one of the other two patterns.
Is there a C-like continue
action that will move on the next line ignoring all other condition checks for the current line?
I suppose I could use something like ((NR > 1) && (!/^xyzzy:/)) {print}
as the third rule but that seems rather ugly to me.
Alternatively, is there another way to do this?
awk is a line-oriented language. Each rule's action has to begin on the same line as the pattern. To have the pattern and action on separate lines, you must use backslash continuation; there is no other option. In this case, it looks like the backslash would continue the comment onto the next line.
Using the grep Command. If we use the option '-A1', grep will output the matched line and the line after it.
The conditional statement executes based on the value true or false when if-else and if-elseif statements are used to write the conditional statement in the programming. Awk supports all types of conditional statements like other programming languages.
Default behavior of Awk: By default Awk prints every line of data from the specified file. In the above example, no pattern is given. So the actions are applicable to all the lines. Action print without any argument prints the whole line by default, so it prints all the lines of the file without failure.
Use the keyword next
as your action
This keyword is often useful when you want to iterate over 2 files; sometimes it's the same file that you want to process twice.
You'll see the following idiom:
awk ' FNR==NR { < stuff that works on file 1 only > next } { < stuff that works on file 2 only > }' ./infile1 ./infile2
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