简体   繁体   中英

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..

<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.

@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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM