sed line range, all but the last line

前端 未结 5 1041
小蘑菇
小蘑菇 2020-12-08 04:48

You can specify a range of lines to operate on. For example, to operate on all lines, (which is of course the default):

sed -e \"1,$ s/a/b/\"
相关标签:
5条回答
  • 2020-12-08 05:04

    This command works, too

    sed '$d'
    
    0 讨论(0)
  • 2020-12-08 05:08

    I know it is not sed, but I feel that head gets the easiest and most flexible way:

    head -n -1 the-file
    

    Use -2, -3... instead of -1, to retrieve all but the last two lines, etc.

    0 讨论(0)
  • 2020-12-08 05:15
    sed -e "$ ! s/a/b/"
    

    This will match every line but the last. Confirmed with a quick test!

    0 讨论(0)
  • 2020-12-08 05:16

    In a more general sense, this issue requires you to edit a stream by specifying a range with one of the range limits being an offset from the end-of-file. The following example shows how to do this. In this example I am printing out all the lines of a file, beginning with the 5th line from the last line, and ending with the last line. In your case, you can set OFFSET = -1instead of OFFSET = -5.

    (( OFFSET = -5 )); (( N1 = $(cat pgen.c | wc -l) + OFFSET )); sed -n "$N1,\$p" thefile
    

    This command can be entered in one line.

    0 讨论(0)
  • 2020-12-08 05:23

    Well, you could hack it with something like this:

    sed -e "1,$(($(cat the-file | wc -l) - 1))s/a/b/"
    

    Or, you could use tail instead:

    (tail +1 the-file) | sed -e s/a/b/; tail -1 the-file
    
    0 讨论(0)
提交回复
热议问题