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

前端 未结 22 734
走了就别回头了
走了就别回头了 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:18

    In docker, this worked for me:

    head --lines=-N file_path >> file_path
    
    0 讨论(0)
  • 2020-11-28 18:20

    This might work for you (GNU sed):

    sed ':a;$!N;1,4ba;P;$d;D' file
    
    0 讨论(0)
  • 2020-11-28 18:20

    This will remove the last 12 lines

    sed -n -e :a -e '1,10!{P;N;D;};N;ba'
    
    0 讨论(0)
  • 2020-11-28 18: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

    0 讨论(0)
  • 2020-11-28 18:21

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

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

    0 讨论(0)
  • 2020-11-28 18:22

    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.

    0 讨论(0)
提交回复
热议问题