Saturday, August 11, 2007

Display Specific Lines in a File using sed

I'm often asked how to show specific lines in a file. The utility I use for this task is the powerful string editor or sed. Here's a brief example of its use.

For illustration purposes, I'm using the cat -n filename to show the line numbers in this script.

# cat -n filename
...
8 for i in $*
9
10 do
11
12 typeset -i16 hex
13 hex=$i
14 print $i equals $hex in hexadecimal
15
16 typeset -i8 oct
17 oct=$i
18 print $i equals $oct in octal
19
20 typeset -i2 bin
21 bin=$i
22 print $i equals $bin in binary
23
24 print
25 done
...

Prints out the for loop without displaying the line numbers
# sed -n 8,25p filename | tee for_loop

4 comments:

UX-admin said...

One could also use awk:

awk 'NR >= 8 && NR <= 25' filename

esofthub said...

ux-admin -- As always, thanks for the tip.

Anonymous said...

that was really helpful. thanks!

Anonymous said...

foo.txt contains
1
2
3
4
5

head -n 4 foo.txt | tail -n 2

displays
3
4