Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk to search a pattern and print lines with pattern and one more condition

Tags:

sed

awk

I have a input file as shown below:

SR  policy name    state             error code
1   backup01       successful         0
2   backup01       fail               13
3   backup01       fail               58
4   backup02       successful         0
5   backup02       successful         0
6   backup02       successful         0

I want to have an output where if any line for a particular policy (example backup01 has a line with "fail" state, it will only show "fail" state lines and will not show the "success" lines. Similarly where all lines of a policy (example backup02) have a state "successful" it will print all the "successful" state lines.

2   backup01       fail               13
3   backup01       fail               58
4   backup02       successful         0
5   backup02       successful         0
6   backup02       successful         0

I have tried using awk with little success, but not able to get ahead with a final solution.

awk '{if ($4 == 0) {print $0} else if($4 !=0 && $4 == 0) {print $0}}' input_file.txt

any other way using sed or other tool is also fine. ALso header from input file can also be ignored.

like image 390
Sandeep_Patil Avatar asked Oct 21 '25 03:10

Sandeep_Patil


1 Answers

I would harness GNU AWK following way, let file.txt content be

SR  policy name    state             error code
1   backup01       successful         0
2   backup01       fail               13
3   backup01       fail               58
4   backup02       successful         0
5   backup02       successful         0
6   backup02       successful         0

then

awk 'NR>1{arr[$2][$3]=arr[$2][$3] RS $0}END{for(i in arr){print substr(arr[i]["fail" in arr[i]?"fail":"successful"],2)}}' file.txt

gives output

2   backup01       fail               13
3   backup01       fail               58
4   backup02       successful         0
5   backup02       successful         0
6   backup02       successful         0

Explanation: for lines beyond 1st I populate 2D array, with first key being policy name and second state, I append whole line using row separator so values are lines separated by newlines. When file is processed I go through said array and print what is under fail if it is is available for given policy name else what is under successful. I start printing at 2nd character due to leading newline which appear due to way I populate array. Disclaimer: this solution assumes you are accepting any order of lines in output, if this does not hold do not use it.

(tested in GNU Awk 5.1.0)

like image 184
Daweo Avatar answered Oct 24 '25 03:10

Daweo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!