Wednesday, March 12, 2014

S&P 3 - tail and head to show lines middle of the file / head - tail command to show lines in between x and y

A close friend of mine asked me - which command will show the lines in between 90 and 100?

looks like a simple question, isnt. but its a tricky one.

He gave me the choices as well:
1. tail -n 90-100 file
2. head -n 100 | tail -n 10
3. head -n 90-100 file
4. list -n 90-100 file

after seeing the choices, it is confusing, isnt?!?!

ok, lets remember these 5 rules:

rule 1. head -20 <filename> ---will show first 20 lines of the <filename>.
rule 2. tail -20 <filename> ---will show the last 20 lines of the <filename>
 

3. remember a rule, head or tail, dont work with just the numbers. the numbers should have a minus sign or plus sign.
(if you try head 20 filename, it will look for a filename 20 and secondfile filename, and it will show first ten lines from both file, provided that a file

exists with the name "20". or it will say, "20" file does not exist and it will show the first ten lines of the filename)
head <N> <filename>
tail <N> <filename>

4. in case of head, avoid "+n"

to summarize:

tail n <filename>  ==> it wont work
tail -n <filename>  =======> will show last "n" lines
tail +n <filename> (rule 5, please check below)

head -n <filename>  =======> will show first "n" lines
head +n <filename> ==> it wont work
head n <filename>  ==> it wont work
 

rule 5. tail +n <filename> will show the file starting from line n, till the end of the file. please note it looks like it works only on Posix standard tail. so,
better to avoid this as well.


ok now, to show the lines in between 90 to 100:
-- show first 100 lines, cut out and show only last ten lines(90 to 100)
head -100 <filename> | tail -10

1 comment:

  1. Excellent Inventsekar great explanation with example.

    Appreciate your work.

    ReplyDelete