Friday, October 26, 2018

awk if/else conditions and printing last line



My two example files looks like this:



F1



Red -
Blue -
Green -



F2



Yellow +
Pink +
ColorX +


I need awk script to print first/last line depending on $2 Field (If $2 == "+" -- print first line; else -- print last line).




I managed to write awk script that prints first line, but how can I add else in order to print last line?



awk '{if (NR == 1 && $2 == "+") print}' F2
Yellow +


How can I modify this code to input F1 and get Green - printed?



Maybe it is possible to add something like this: awk '{if (NR == 1 && $2 == "+") print ; else {END print} }'



Answer



awk 'NR == 1 && $2 == "+" { print ; p=1 ; exit } 
END { if (p != 1) { print $0 } }' INPUTFILE


Note: this assumes, that if the first line does not contains '+' the last line must get printed.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...