Olga
Olga

Reputation: 1022

sed get text between lines

I have prompt history in a file:

[user@host path]# echo $first 
14556
....
[user@host path]# echo $second
65541
....
[user@host path]# echo $first
12345
[user@host path]# command
unknow number of rows
[user@host path]# echo $second
54321
[user@host path]#

$first and $second are random values and there many of them in a file. How to get text between echo $first and echo $second outputs from the end of a file? i.e.

[user@host path]# command
unknow number of rows
[user@host path]# echo $second

It seems I can use

sed -n '/WORD1/,/WORD2/p' file

but I don't know how to write $first and $second instead of WORD1 and WORD2

then I need to get only (unknow number of rows). To do it I will use\

sed -e '1d' -e '$d' file

Upvotes: 3

Views: 7104

Answers (2)

Chris Seymour
Chris Seymour

Reputation: 85765

Using a print flag with awk and tac:

$ tac file | awk '/\$first/{p=0;exit}p;/\$second/{p=1}' | tac
12345
[user@host path]# command
unknow number of rows

This gets the lines after the last occurrence of $first and before the occurrence of $second.

Upvotes: 1

Chirlo
Chirlo

Reputation: 6122

If i understood it right, you can simply write:

sed -n "/$first/, /$second/ p"  file

The " allows bash to evaluate the variables, unlike '

Upvotes: 2

Related Questions