Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

sed

A sed command used in a script as following:

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

I knows that

s/^ENABLE_DEBUG.*/ENABLE_DEBUG = YES/

is to substitutes line prefix

ENABLE_DEBUG as ENABLE_DEBUG = YES

But no idea about the meaning of

0,/^ENABLE_DEBUG.*/

Anyone can help me?

like image 655
orionlin Avatar asked Aug 07 '15 04:08

orionlin


1 Answers

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.

like image 182
John1024 Avatar answered Oct 25 '22 10:10

John1024