How to search a text in file and retrieve required lines following it with UNIX command?

I have requirement to search for a text in the file and retrieve required lines that is user defined with unix command.

Eg:

Find the text UNIX in the below file and need to return Test 8 & Test 9

Test 1
Test 2
Test 3
Test 4
UNIX
Test 5
Test 6
Test 7
Test 8
Test 9

Result can be:

Test 8
Test 9

Please suggest an answer with examples.

Thanks in advance :slight_smile:

Welcome to the forum.

Any attempts / ideas / thoughts from your side? Please demonstrate why and by which logic the two lines should be selected once the "UNIX" test was found..

I came across below UNIX command, this will return matching text plus the line following it.

sed -n '/UNIX/,+1p' file.txt >newfile.txt

In the above mentioned example it should return below

UNIX
Test 5

But this command is not working for me.

The logic I am looking for is to match a file pattern and return the line after the match which is specified by me. (i.e I need to choose which line to return after the text match)

I need some working Unix command for this requirement.

Thanks!!

What error / output do you get?

If you're using Linux, or have access to GNU grep, so can also do this with:

$ grep -A1 UNIX file
UNIX
Test 5

or with something like:

$ sed -n '/UNIX/{N;p;}' file
UNIX
Test 5
1 Like

And how would you supply the info "after the match which is specified by me". Please give the entire picture, don't have people in here worm it out of you bit by bit.

Hmm. I seem to have missed the first post (was referring to post #3).

I'm sure some of our sed experts could do this with sed , but I find ed with a here-document much easier to deal with when using offsets from a line that matches a pattern. With a POSIX conforming shell (or any shell that uses Bourne shell syntax and supports arithmetic expansions) the following script should do what you want with either ed or ex :

BRE=UNIX	# Basic Regular Expression to search for.
after=4		# Lines after match where first line to be printed will be found
count=2		# Number of lines to print.
file=file	# Pathname of file to be searched.

ed -s "$file" <<EOF
/$BRE/+$after;.+$((count - 1))p
q
EOF
1 Like

Hi Scott your post was very useful. Also can you please advice whether by using UNIX command we can match a certain pattern and return the following lines which is user-defined. By User-defined, I mean the text file will be in a format so as to match a file pattern and return another part of the file by ignoring few lines.

In the above mentioned example, I want to find the text UNIX and just return below

Test 8
Test 9

It will be great if the result is copied to a new text file.

Thanks in advance :slight_smile:

Skip 2 lines after UNIX ?

awk 'found_unix_line==1 && skip_line_count++ > 2 {print $0} ; /UNIX/ {found_unix_line=1}' input_file > new_text_file