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

独自空忆成欢 提交于 2019-11-27 05:15:55

问题


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

回答1:


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).




回答2:


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



回答3:


A simple solution using awk:

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



回答4:


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




回答5:


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




回答6:


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...




回答7:


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.




回答8:


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"


来源:https://stackoverflow.com/questions/3507999/whats-the-opposite-of-head-i-want-all-but-the-first-n-lines-of-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!