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

前端 未结 22 783
走了就别回头了
走了就别回头了 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条回答
  •  [愿得一人]
    2020-11-28 18:29

    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!

    If you want to save it into a new file, the code is:

    sed -i '2174,$d' file > outputfile
    

提交回复
热议问题