Home > OS >  grep specific word and other words after it
grep specific word and other words after it

Time:11-17

I have a file with a lot of data, I want to search for specific word and when found it, grep it and two other words after it, then keep searching the file to find this specific word again and do the same as I did previously.

Example:

Test::All 123

Availability: Available

State: Enable

**Test:: Member PUT

Availability: Available

State: Enable****

Test:: Many 345

Availability: Available

State: Enable

now I want to search Test:: Member and grep it along with the word Availability and word State. and skip Availabilty and State if it came after any other grep criteria other than Test:: Member

Thanks, Talal

grep -iE '(Test:: Member|availability|State)'

... but I get Availability and state under the other Test:: ALL and Many.

CodePudding user response:

sed is good for fairly complex conditional "greps".

$: sed -En '/Test:: Member/,/Test:: /{ /Availability|State/p; /Test:: Member/{p;n;}; /Test:: /q; }' file
**Test:: Member PUT
Availability: Available
State: Enable****

/Test:: Member/,/Test:: /{...} checks from this line to the nest Test::, and performs the actions inside the braces on each of those lines.

/Availability|State/p; prints the lines that match (I skip others, like blank lines).

/Test:: Member/{p;n;}; says on that line,

  • p show the line itself
  • n skip to the next line without doing any more of these commands on this one.

/Test:: /q; says (if it gets this far) quit the files on the nest Test:: line.

You get the idea.

CodePudding user response:

Supposing that you have the structure as shown above you can try:

grep 'Test::Member' -A2

CodePudding user response:

With :

$ perl -0ne 'print "$1\n" if /(Test::.*?State: \w )/ms' file
Test::All 123

Availability: Available

State: Enable
  • Related