3

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 ??

oguz ismail
  • 1
  • 16
  • 47
  • 69
moth
  • 1,833
  • 12
  • 29
  • 1
    Attached dupe was a wrong one(it wasn't answering complete question of OP, it was answering only part of OP's question, which OP already mentioned in OP's question), so re-opened the question. – RavinderSingh13 Feb 11 '21 at 12:47

1 Answers1

7

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.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93