5

I know people use : instead of / when they are dealing with paths, but what does :g do in the following sed action?

Why is path1 between quotation mark? Can anyone explain the action of this code?

sed -i -e s:INPUT_REPLACE:"${path1}":g ${path2}
1
  • Note (1) if the s:INPUT_REPLACE:"${path1}":g syntax looks weird to you, and you want an alternative, you can use "s:INPUT_REPLACE:${path1}:g" instead (moving the quotes from the inside to the beginning and the end), and (2) you should probably put "$path2" into quotes, too. (You can leave the braces in; e.g., "${path2}", but they are unnecessary in this context. See this and this for more information) Sep 8, 2016 at 3:34

1 Answer 1

11

The colons : are delimiters for the pattern (left) and substitution (right). g tells sed to "globally" substitute (change everything that matches the pattern on each line, rather than only the first on a given line).

Three colons are used, because you need three delimiters. So :g is really two things: the last delimiter and the modifier "g".

The quotation mark is used in case this part of the expression "${path1}" contains some character (when the variable is substituted) that would make an error in the command. For instance, if it contained a space or tab, that would break the substitution parameter passed by the shell to sed into two parts (an error).

So... this command

sed -i -e s:INPUT_REPLACE:"${path1}":g ${path2}

tells sed to read/write the same file (the -i option). The file is ${path2}. It looks for lines containing "INPUT_REPLACE", and replaces that string on each line with whatever is in the variable ${path1}. It does that for each occurrence of "INPUT_REPLACE" on each line.

By the way: if "${path1}" contains "INPUT_REPLACE" (or the substitution makes an occurrence), sed will not redo things and substitute again. It only does this on the initial matches.

The -i option is not in POSIX, but is available with Linux and BSDs.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .