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

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

    A funny & simple sed and tac solution :

    n=4
    tac file.txt | sed "1,$n{d}" | tac
    

    NOTE

    • double quotes " are needed for the shell to evaluate the $n variable in sed command. In single quotes, no interpolate will be performed.
    • tac is a cat reversed, see man 1 tac
    • the {} in sed are there to separate $n & d (if not, the shell try to interpolate non existent $nd variable)

提交回复
热议问题