开发者

What's the opposite of head? I want all but the first N lines of a file

Given a text file of unknown length, how can I read, for example all but the first 2 lines of the file? I know tail will give me the last N lines, but I don't know what N is ahead of time.

So for a file

AAAA
BBBB
CCCC开发者_运维技巧
DDDD
EEEE

I want

CCCC
DDDD
EEEE

And for a file

AAAA
BBBB
CCCC

I'd get just

CCCC


tail --help gives the following:

  -n, --lines=K            output the last K lines, instead of the last 10;
                           or use -n +K to output lines starting with the Kth

So to filter out the first 2 lines, -n +3 should give you the output you are looking for (start from 3rd).


Assuming your version of tail supports it, you can specify starting the tail after X lines. In your case, you'd do 2+1.

tail -n +3

[mdemaria@oblivion ~]$ tail -n +3 stack_overflow.txt
CCCC
DDDD
EEEE


A simple solution using awk:

awk 'NR > 2 { print }' file.name


Try sed 1,2d. Replace 2 as needed.


tail -n +linecount filename will start output at line linecount of filename, so tail -n +3 filename should do what you want.


Use this, supposing the first sample is called sample1.dat then tail --lines=3 sample1.dat which would print all lines from the 3rd line to the last line.

For the second sample, again suppose it is called sample2.dat it would be tail --lines=-1 sample2.dat which would print the last line...


The head function supports this with negative numbers.

head --help

-n, --lines=[-]K         print the first K lines instead of the first 10;
                         with the leading '-', print all but the last
                         K lines of each file

For example, a positive number prints the first 2 lines.

 head -n +2

 AAAA
 BBBB

A negative number prints all except for the first 2 lines.

head -n -2

CCCC
DDDD
EEEE

Note that unlike with tail this does not require prior knowledge of the total number of lines in a file. It excludes the first 2 lines regardless of how many lines there are. Negative numbers for tail -n -2 can similarly be used to remove the last 2 lines of a file.

Note this uses GNU head version 8.22. This feature may not have been available at the original time of release. It is now available even if fairly old linux distros.


I really don't know how to do it from just tail or head but with the help of wc -l (line count) and bash expression, you can achieve that.

tail -$(( $( wc -l $FILE | grep -Eo '[0-9]+' ) - 2 )) $FILE

Hope this helps.


using awk to get all but the last 2 line

awk 'FNR==NR{n=FNR}FNR<=n-3{print}' file file

awk to get all but the first 2 lines

awk 'NR>2' file

OR you can use more

more +2 file

or just bash

#!/bin/bash

i=0
while read -r line
do
  [[ $i > 1 ]] && echo "$line"
  ((i++))
done <"file"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜