3

Here is my sample file

user@linux:~$ cat file.txt 
Line 1
Line 2
Line 3
Line 4
Line 5
user@linux:~$ 

I can print line 2-4 with grep -A2 'e 2' file.txt

user@linux:~$ grep -A2 'e 2' file.txt 
Line 2
Line 3
Line 4
user@linux:~$ 

I can also print out the line number as well with grep -n

user@linux:~$ grep -nA2 'e 2' file.txt 
2:Line 2
3-Line 3
4-Line 4
user@linux:~$ 

Also, the same thing can be accomplished with sed -n 2,4p file.txt

user@linux:~$ sed -n 2,4p file.txt 
Line 2
Line 3
Line 4
user@linux:~$ 

But I'm not sure how to print out the line number with sed

Would it be possible to print out the line number with sed?

  • 1
    Why sed and not awk 'NR==2,NR==4{print NR" "$0}' file.txt. – simlev Jun 20 at 15:05
  • Thanks. Didn't know it can be accomplished with awk. I've just reading about sed and wondering if it can do the same thing. – Sabrina Jun 20 at 15:07
  • @steeldriver very good comment, sry I didn't see it before posting below. Please create an answer. – simlev Jun 20 at 15:42
  • 1
    @kusalananda Why did you delete your answer? It contained some useful explanations and while I was reading it...puff. – simlev Jun 20 at 15:44
  • @kusalananda, I was reading the answer when you removed it. Could you please put it back. That post might be useful to others too – Sabrina Jun 20 at 16:00
5

AWK:

awk 'NR==2,NR==4{print NR" "$0}' file.txt

Double sed:

sed '2,4!d;=' file.txt | sed 'N;s/\n/ /'

glen jackmann's sed and paste:

sed '2,4!d;=' file.txt | paste -d: - -

Perl:

perl -ne 'print "$. $_" if ($.>=2 and $.<=4)' file.txt

Equivalent Perl:

perl -ne 'print "$. $_" if $.==2..$.==4' file.txt

cat and sed:

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

Also see this answer to a similar question.

A bit of explanation:

  • sed -n '2,4p' and sed '2,4!d;=' do the same thing: the first only prints lines between the second and the fourth (inclusive), the latter "deletes" every line except those.

  • sed = prints the line number followed by a newline. See the manual.

  • cat -n in the last example can be replaced by nl or grep -n ''.

  • 2
    also sed+paste is very readable: sed '2,4!d;=' file | paste -d: - - – glenn jackman Jun 20 at 15:57
2

I have done by below mentioned 2 methods

Method1

awk '/2/{x=NR+2}(NR<=x){print NR"-"$0 }' filename

command

2-Line 2
3-Line 3
4-Line 4

Method2

sed -n '{;=;p}' filename| sed "N;s/\n/ /g"| sed -n '/2/,+2p'

output

2 Line 2
3 Line 3
4 Line 4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.