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

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

    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
    

提交回复
热议问题