Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get awk to move to next line when a condition has been actioned?

Tags:

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?

like image 488
paxdiablo Avatar asked Jan 04 '12 06:01

paxdiablo


People also ask

How do you go to the next line in awk?

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.

How do you go to the next line after grep?

Using the grep Command. If we use the option '-A1', grep will output the matched line and the line after it.

How do you use condition in awk?

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.

Does awk process line by line?

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.


1 Answers

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 
like image 83
SiegeX Avatar answered Oct 01 '22 06:10

SiegeX