0

I have a file test.txt, with contents like theese:

line random text 1
line random text 2
line random text 3
line particular exception 
line except detail 1
line except detail 2
line except detail 3
....
line random text 14
line random text 15
line random text 16
line particular exception 
line except detail 1
line except detail 2
line except detail 3
.....

I want to output (for further grep) the file contents filtering where "particular exception" appears, and filtering the "particular exception" details that appear AFTER it (allways 3 lines).

The logical command i thought of is this:

cat test.txt | grep -v -A 3 "particular exception"

But it doesn't work as i expected.

What is the correct way of doing this?

For some context, what i'm trying to do is to find exceptions in a log file EXCEPT a particular one that is constantly repeating itself, so first i want to clear it.

3

Instead of using grep, you can use GNU sed:

sed -e '/particular exception/,+3d' test.txt

This finds lines that match particular exception and deletes them and the three lines after them.

  • I wasn't aware of sed. It worked very well, thank you. I'll mark as correct answer tomorrow. – ndelucca Apr 6 '18 at 14:22
0

Using awk:

$ awk -v n=3 -v p='particular exception' 'match($0,p) { skip=n+1 } --skip < 0' test.txt
line random text 1
line random text 2
line random text 3
....
line random text 14
line random text 15
line random text 16
.....

The number of lines of trailing context to skip is given on the command line with e.g. -v n=3 and the regular expression to match is also given on the command line as -v p='expression'.

The variable skip will be decreased by one for every line read, and the script will print the current line whenever the variable skip is less than zero. When the pattern of interest is found, the skip variable gets the value of n + 1 which means that the current line and n more lines will be skipped.

match($0,p) could also be written $0 ~ p.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.