moth
moth

Reputation: 2379

sed to operate on a range of lines plus a single line

Let's say I have a file file.txt:

hello 
world
hi
there
this
wow

I know sed can operate on one line like:

sed -n '2p' file.txt

or a range :

sed -n '2,4p' file.txt

but how to operate on one specific line plus a range ?

sed -n '1line and 4,5' file.txt or in words print the first line and the range from 4th to 5th line ??

Upvotes: 3

Views: 780

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133518

Could you please try following. Written and tested with shown samples in GNU sed. This will print line which has string hello and will print lines from 2nd line to 4th line.

sed -n '/hello/p;2,4p' Input_file

OR to give single line number along with a lines range try following:

sed -n '1p;2,4p' Input_file

Explanation: Using -n option to stop printing for all lines first. Then checking condition if line contains /hello then printing that line by p option. After that giving 2nd statement separated by ; to print a range from 2nd line to 4th line number.

Upvotes: 7

Related Questions