How to use sed to remove the last n lines of a fil

2019-01-07 02:54发布

I want to remove some n lines from the end of a file. Can this be done using sed?

For example, to remove lines from 2 to 4, I can use

$ sed '2,4d' file

But I don't know the line numbers. I can delete the last line using

$sed $d file

but I want to know the way to remove n lines from the end. Please let me know how to do that using sed or some other method.

20条回答
成全新的幸福
2楼-- · 2019-01-07 03:12

Try the following command:

n = line number
tail -r file_name | sed '1,nd' | tail -r
查看更多
男人必须洒脱
3楼-- · 2019-01-07 03:14

I prefer this solution;

head -$(gcalctool -s $(cat file | wc -l)-N) file

where N is the number of lines to remove.

查看更多
一夜七次
4楼-- · 2019-01-07 03:14

I don't know about sed, but it can be done with head:

head -n -2 myfile.txt
查看更多
该账号已被封号
5楼-- · 2019-01-07 03:15

With the answers here you'd have already learnt that sed is not the best tool for this application.

However I do think there is a way to do this in using sed; the idea is to append N lines to hold space untill you are able read without hitting EOF. When EOF is hit, print the contents of hold space and quit.

sed -e '$!{N;N;N;N;N;N;H;}' -e x

The sed command above will omit last 5 lines.

查看更多
Lonely孤独者°
6楼-- · 2019-01-07 03:19

Most of the above answers seem to require GNU commands/extensions:

    $ head -n -2 myfile.txt
    -2: Badly formed number

For a slightly more portible solution:

     perl -ne 'push(@fifo,$_);print shift(@fifo) if @fifo > 10;'

OR

     perl -ne 'push(@buf,$_);END{print @buf[0 ... $#buf-10]}'

OR

     awk '{buf[NR-1]=$0;}END{ for ( i=0; i < (NR-10); i++){ print buf[i];} }'

Where "10" is "n".

查看更多
狗以群分
7楼-- · 2019-01-07 03:19
sed -n ':pre
1,4 {N;b pre
    }
:cycle
$!{P;N;D;b cycle
  }' YourFile

posix version

查看更多
登录 后发表回答