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

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

    This will remove the last 3 lines from file:

    for i in $(seq 1 3); do sed -i '$d' file; done;

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

    To delete last 4 lines:

    $ nl -b a file | sort -k1,1nr | sed '1, 4 d' | sort -k1,1n | sed 's/^ *[0-9]*\t//'   
    
    0 讨论(0)
  • 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)
    0 讨论(0)
  • 2020-11-28 18:28

    From the sed one-liners:

    # delete the last 10 lines of a file
    sed -e :a -e '$d;N;2,10ba' -e 'P;D'   # method 1
    sed -n -e :a -e '1,10!{P;N;D;};N;ba'  # method 2
    

    Seems to be what you are looing for.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • Most of the above answers seem to require GNU commands/extensions:

        $ head -n -2 myfile.txt
        -2: Badly formed number
    

    For a slightly more portible solution:

         perl -ne 'push(@fifo,$_);print shift(@fifo) if @fifo > 10;'
    

    OR

         perl -ne 'push(@buf,$_);END{print @buf[0 ... $#buf-10]}'
    

    OR

         awk '{buf[NR-1]=$0;}END{ for ( i=0; i < (NR-10); i++){ print buf[i];} }'
    

    Where "10" is "n".

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