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

From the sed one-liners:

# delete the last 10 lines of a file
sed -e :a -e '$d;N;2,10ba' -e 'P;D'   # method 1
sed -n -e :a -e '1,10!{P;N;D;};N;ba'  # method 2

Seems to be what you are looing for.

查看更多
贼婆χ
3楼-- · 2019-01-07 03:29

This might work for you (GNU sed):

sed ':a;$!N;1,4ba;P;$d;D' file
查看更多
Melony?
4楼-- · 2019-01-07 03:30

You can get the total count of lines with wc -l <file> and use

head -n <total lines - lines to remove> <file>

查看更多
Rolldiameter
5楼-- · 2019-01-07 03:32

Use sed, but let the shell do the math, with the goal being to use the d command by giving a range (to remove the last 23 lines):

sed -i "$(($(wc -l < file)-22)),\$d" file

To remove the last 3 lines, from inside out:

$(wc -l < file)

Gives the number of lines of the file: say 2196

We want to remove the last 23 lines, so for left side or range:

$((2196-22))

Gives: 2174 Thus the original sed after shell interpretation is:

sed -i 2174,$d file

With -i doing inplace edit, file is now 2173 lines!

查看更多
Fickle 薄情
6楼-- · 2019-01-07 03:34

I came up with this, where n is the number of lines you want to delete:

count=`wc -l file`
lines=`expr "$count" - n`
head -n "$lines" file > temp.txt
mv temp.txt file
rm -f temp.txt

It's a little roundabout, but I think it's easy to follow.

  1. Count up the number of lines in the main file
  2. Subtract the number of lines you want to remove from the count
  3. Print out the number of lines you want to keep and store in a temp file
  4. Replace the main file with the temp file
  5. Remove the temp file
查看更多
看我几分像从前
7楼-- · 2019-01-07 03:36

It can be done in 3 steps:

a) Count the number of lines in the file you want to edit:

 n=`cat myfile |wc -l`

b) Subtract from that number the number of lines to delete:

 x=$((n-3))

c) Tell sed to delete from that line number ($x) to the end:

 sed "$x,\$d" myfile
查看更多
登录 后发表回答