What's the opposite of head? I want all but th

2019-01-16 10:52发布

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

8条回答
放荡不羁爱自由
2楼-- · 2019-01-16 11:04

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.

查看更多
Evening l夕情丶
3楼-- · 2019-01-16 11:09

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

查看更多
爷的心禁止访问
4楼-- · 2019-01-16 11:09

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"
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-16 11:10

A simple solution using awk:

awk 'NR > 2 { print }' file.name
查看更多
老娘就宠你
6楼-- · 2019-01-16 11:11

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

查看更多
【Aperson】
7楼-- · 2019-01-16 11:13

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

查看更多
登录 后发表回答