Sed to print out the line number
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'
andsed '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 bynl
orgrep -n ''
.
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