what is meaning of sed -e 's|PATH="\(.*\)"|PATH="/opt/man/common/bin:\1"|g' -i /etc/environment line

Issue

what is meaning of following command?

sed -e 's|PATH="\(.*\)"|PATH="/opt/man/common/bin:\1"|g' -i /etc/environment

Solution

It substitutes all the instances of

PATH="somestring"

with

PATH="/opt/man/common/bin:somestring"

in the file /etc/environment

In detail

  • s|string1|string2| substitutes string1 with string2
    • the delimiter (in this case |) is defined by the character following the substitute command (s). More common is /.
    • the flag g at the end tells sed to substitute all non-overlapping matches (and not only the first one)
    • the \( and \) define a group (in this case everything between the quotes)
    • the \1 is a back-reference to the first group
  • -i is telling sed to apply the changes directly in the file (inline) instead of writing to standard output.

Edit

As pointed out in the comments this regular expression is very fragile.

  • It will match the string anywhere (not only after a blank or the beginning of a line). It will for example match CDPATH="string"
  • It will not match strings delimited by '. It will not match PATH='somepath'.
  • It will match strings in comments. For example # some comment with PATH="" in the text
  • It will match inside other strings, for example STRING='PATH="somepath"

Answered By – Matteo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published