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

前端 未结 22 812
走了就别回头了
走了就别回头了 2020-11-28 18:12

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          


        
22条回答
  •  萌比男神i
    2020-11-28 18:41

    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

提交回复
热议问题