Karthi1234
Karthi1234

Reputation: 1017

bash grep for string and ignore above one line

One of my script will return output as below,

NameComponent=Apache
Fixed=False
NameComponent=MySQL
Fixed=True

So in the above output, I am trying to ignore the below output using grep grep -vB1 'False' which seems not working,

NameComponent=Apache
Fixed=False

Is it possible to perform this using grep or is any better way with awk..

Upvotes: 0

Views: 67

Answers (3)

nobody27
nobody27

Reputation: 61

If I understand the question correctly you will always have a line before "Fixed=..." and you want to print both lines if and only if "Fixed=True"

The following awk should do the trick:

< command > | awk 'BEGIN {prev='NA'} {if ($0=="Fixed=True") {print prev; print $0;} prev=$0;}'

Note that if the first line is "Fixed=True" it will print the string "NA" as the first line.

Upvotes: 0

P....
P....

Reputation: 18411

<some-command> |tac |sed -e '/False/ { N; d}' |tac
NameComponent=MySQL
Fixed=True

For every line that matches "False", the code in the {} gets executed. N takes the next line into the pattern space as well, and then d deletes the whole thing before moving on to the next line. Note: using multiple pipes is not considered as good practice.

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133770

@Karthi1234: If your Input_file is same as provided samples then try:

awk -F' |=' '($2 != "Apache" && $2 != "False")'   Input_file

First making field separator as a space or = then checking here if field 2nd's value is not equal to sting Apache and False and mentioned no action to be performed so default print action will be done by awk.

EDIT: as per OP's request following is the code changed one, try:

awk '!/Apache/ && !/False/'   Input_file

You could change strings too in case if these are not the ones which you want, logic should be same.

EDIT2: eg--> You could change values of string1 and string2 and increase the conditions if needed as per your requirement.

awk '!/string1/ && !/string2/'   Input_file

Upvotes: 0

Related Questions