2

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}
  • 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) – G-Man Sep 8 '16 at 3:34
8

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.