2016. május 13., péntek

Using awk with two actions for two conditions

You can read a lot about awk. There are a lot of tutorials about it. It's very useful tool if you want to filter file contents or simply filter/cut the output of a previous command in the shell. Yes, this is about some weird Linux stuff...

The tool usage is quite complex at first sight, but after you learn the basics of it, it becomes quite easy. It does not require too much time to use awk on a basic level.

But sometimes you face a problem which is not so straightforward for a newbie. Like I did today.

Problem: how to filter for diferrent fields (action) in two separate lines which are selected by different conditions? In other words: I want to have field 2 printed if the line contains THIS and want to have field 5 printed if the line contains THAT.

Usually we use awk like this: print field 5 if the line contains this. Or print field 4 and 6 if the line contains this and that. But in my problem the conditions and actions are different.

After investigating the case with my friend Google I found a solution: the conditional if statement! Wow...as awk is not just a command line tool, but a programming language, the solution is to think like a programmer / coder.

Here it is :

2_lines_of_output_from_another_command | awk '{if ($3 == "condition1") print $1; else print $4;}'

This is implemented for a 2 lines input because I got rid of everything else. The main point is to use if / else and you can use "if else if else"... just be careful with the different closing signs.

That's it, I hope awk is not so aw(k)ful after reading this!