What is the meaning of “0,/xxx” in sed?

后端 未结 1 1599
栀梦
栀梦 2021-01-13 14:44

A sed command used in a script as following:

sed -i \"0,/^ENABLE_DEBUG.*/s/^ENABLE_DEBUG.*/ENABLE_DEBUG = YES/\" MakeConfig

I knows that

相关标签:
1条回答
  • 2021-01-13 15:26

    0,/^ENABLE_DEBUG.*/ means that the substitution will only occur on lines from the beginning, 0, to the first line that matches /^ENABLE_DEBUG.*/. No substitution will be made on subsequent lines even if they match /^ENABLE_DEBUG.*/

    Other examples of ranges

    This will substitute only on lines 2 through 5:

    sed '2,5 s/old/new/'
    

    This will substitute from line 2 to the first line after it which includes something:

    sed '2,/something/ s/old/new/'
    

    This will substitute from the first line that contains something to the end of the file:

    sed '/something/,$ s/old/new/'
    

    POSIX vs. GNU ranges: the meaning of line "0"

    Consider this test file:

    $ cat test.txt
    one
    two
    one
    three
    

    Now, let's apply sed over the range 1,/one/:

    $ sed '1,/one/ s/one/Hello/' test.txt
    Hello
    two
    Hello
    three
    

    The range starts with line 1 and ends with the first line after line 1 that matches one. Thus two substitutions are made above.

    Suppose that we only wanted the first one replaced. With POSIX sed, this cannot be done with ranges. As NeronLeVelu points out, GNU sed offers an extension for this case: it allows us to specify the range as 0,/one/. This range ends with the first occurrence of one in the file:

    $ sed '0,/one/ s/one/Hello/' test.txt
    Hello
    two
    one
    three
    

    Thus, the range 0,/^ENABLE_DEBUG/ ends with the first line that begins with ENABLE_DEBUG even if that line is the first line. This requires GNU sed.

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