Suppress the match itself in grep

Suppose I have many files in the form

First Line Name Second Line Surname Adress Third Line etc etc 

Now I use grep to match the first line. But I do this to find the second line. The second line is not a pattern that can be matched (it just depends on the first line). My regex pattern works, and the command I use is

 grep -rHIin pattern . -A 1 -m 1 

The -A option now prints the line after the match . The -m stops after 1 match (because there is another line that matches my pattern, but I'm only interested in the first match ...)

It really works, but the result is this:

 ./example_file:1: First Line Name ./example_file-2- Second Line Surname Adress 

I read the manual, but could not understand any information or information about this. Now here is the question.

How can I suppress a match ? The output should be in the form:

 ./example_file-2- Second Line Surname Adress 
+4
source share
4 answers

sed to the rescue:

 sed -n '2,${p;n;}' 

A specific sed command starts at line 2 of its input and prints each other line. Run grep output into this and you will only get even lines from grep output.

Explanation of the sed command itself:

2,$ - range of lines from line 2 to the last line of the file

{p;n;} - p enter the current line, then ig n enter the next line (this then repeats)

(In this special case of all even lines, an alternative way to write this would be sed -n 'n;p;' , since we don’t really need special lines for any leading lines. If you want to skip the first 5 lines of the file, that would be impossible, you will need to use the syntax of 6,$ .)

+2
source

You can use sed to print a line after each match:

 sed -n '/<pattern>/{n;p}' <file> 

To get the recursion and file names, you need something like:

 find . -type f -exec sed -n '/<pattern>/{n;s/^/{}:/;p}' \; 
+1
source

You could print the results, but grep -v pattern

0
source

If you've already read the grep book, you can also read the manual for awk , another common Unix tool.

In awk, your task will be solved with simple, simple code. (As for me, I should always update my knowledge of awk syntax by going to the ( info awk ) manual when I want to use it.)

Or you can come up with a solution combining find (to iterate over your files) and grep (to select lines) and head / tail (to discard lines for every single file you don't want). The difficulty with find is being able to work with each file individually, dropping a line to the file.

0
source

Source: https://habr.com/ru/post/1341946/


All Articles