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:20

This will remove the last 12 lines

sed -n -e :a -e '1,10!{P;N;D;};N;ba'
查看更多
Melony?
3楼-- · 2019-01-07 03:21

You could use head for this.

Use

$ head --lines=-N file > new_file

where N is the number of lines you want to remove from the file.

The contents of the original file minus the last N lines are now in new_file

查看更多
别忘想泡老子
4楼-- · 2019-01-07 03:23

Just for completeness I would like to add my solution. I ended up doing this with the standard ed:

ed -s sometextfile <<< $'-2,$d\nwq'

This deletes the last 2 lines using in-place editing (although it does use a temporary file in /tmp !!)

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

To truncate very large files truly in-place we have truncate command. It doesn't know about lines, but tail + wc can convert lines to bytes:

file=bigone.log
lines=3
truncate -s -$(tail -$lines $file | wc -c) $file

There is an obvious race condition if the file is written at the same time. In this case it may be better to use head - it counts bytes from the beginning of file (mind disk IO), so we will always truncate on line boundary (possibly more lines than expected if file is actively written):

truncate -s $(head -n -$lines $file | wc -c) $file

Handy one-liner if you fail login attempt putting password in place of username:

truncate -s $(head -n -5 /var/log/secure | wc -c) /var/log/secure
查看更多
倾城 Initia
6楼-- · 2019-01-07 03:25

If hardcoding n is an option, you can use sequential calls to sed. For instance, to delete the last three lines, delete the last one line thrice:

sed '$d' file | sed '$d' | sed '$d'
查看更多
劳资没心,怎么记你
7楼-- · 2019-01-07 03:25

This will remove the last 3 lines from file:

for i in $(seq 1 3); do sed -i '$d' file; done;

查看更多
登录 后发表回答