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

前端 未结 22 735
走了就别回头了
走了就别回头了 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:30
    sed -n ':pre
    1,4 {N;b pre
        }
    :cycle
    $!{P;N;D;b cycle
      }' YourFile
    

    posix version

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

    For deleting the last N lines of a file, you can use the same concept of

    $ sed '2,4d' file
    

    You can use a combo with tail command to reverse the file: if N is 5

    $ tail -r file | sed '1,5d' file | tail -r > file
    

    And this way runs also where head -n -5 file command doesn't run (like on a mac!).

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

    I don't know about sed, but it can be done with head:

    head -n -2 myfile.txt
    
    0 讨论(0)
  • 2020-11-28 18:35

    Try the following command:

    n = line number
    tail -r file_name | sed '1,nd' | tail -r
    
    0 讨论(0)
  • 2020-11-28 18:35

    I prefer this solution;

    head -$(gcalctool -s $(cat file | wc -l)-N) file
    

    where N is the number of lines to remove.

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

    It can be done in 3 steps:

    a) Count the number of lines in the file you want to edit:

     n=`cat myfile |wc -l`
    

    b) Subtract from that number the number of lines to delete:

     x=$((n-3))
    

    c) Tell sed to delete from that line number ($x) to the end:

     sed "$x,\$d" myfile
    
    0 讨论(0)
提交回复
热议问题