Question

I need to search for a string in a file and print the matching lines together with their next lines in another file. Example:

input file:

>3456/1
A
>1234/2
B
>5678/1
C
>8976/2
D

search for: /2

output:

>1234/2
B
>8976/2
D
Was it helpful?

Solution

Using grep:

$ grep -A1 '/2' file
>1234/2
B
--
>8976/2
D

From the man page:

-A num, --after-context=num
             Print num lines of trailing context after each match.  

You can remove the -- by piping it to grep -v '--' or if you have GNU grep then you can simply do:

$ grep --no-group-separator -A1 '/2' file
>1234/2
B
>8976/2
D

You can re-direct the output of this command to another file.

OTHER TIPS

Using GNU sed

sed -n '/\/2/,+1p' file

Example:

$ sed -n '/\/2/,+1p' file
>1234/2
B
>8976/2
D

Use grep -A

See the man page:

 -A num, --after-context=num
         Print num lines of trailing context after each match.  See also the -B and -C options.
 -B num, --before-context=num
         Print num lines of leading context before each match.  See also the -A and -C options.
-C[num, --context=num]
         Print num lines of leading and trailing context surrounding each match.  The default is 2 and is equivalent to -A 2 -B 2.  Note: no whitespace may be given between the option and its argument.

Here is an example:

%grep -A2 /2 input
>1234/2
B
>5678/1
--
>8976/2
D

Here is grep the correct tool, but using awk you would get:

awk '/\/2/ {print $0;getline;print $0}' file
>1234/2
B
>8976/2
D

PS you should have found this your self, using goolge. This is asked many times.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top