sed with delimiter – any other single character in replacing words or characters

Author:

It is not so known fact that this powerful unix world command

sed

could be used with other delimiter than “/” (when replacing words or characters), which is used in 100% of the time in the Internet examples.
You probably know the syntax from the manual like:

s/regexp/replacement/
              Attempt to match regexp against the pattern space.  If successful, replace that portion matched with replacement.  The replacement may  con‐
              tain  the special character & to refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to
              the corresponding matching sub-expressions in the regexp.

The Internet examples always use “/” as shown in the man, BUT you CAN use “#” instead of “/” for example:

s#regexp#replacement#g

or

s:regexp:replacement:g

or you can even use letter character (not a special character as “!@#$%#^”):

sRregexpRreplacementRg

and with “r” lower case (you see not so readable, but possible!)

srregexprreplacementrg

Here are the examples:

sed 's@else@elllllse@g' test.php
sed 's#else#elllllse#g' test.php
sed 's:else:elllllse:g' test.php
sed 's~else~elllllse~g' test.php
sed 's!else!elllllse!g' test.php
sed 'spelsepelllllsepg' test.php
sed 'sRelseRelllllseRg' test.php
#could be paired with "-i", too
sed 'spelsepelllllsepg' -i test.php
sed 'sRelseRelllllseRg' -i test.php

What does it mean to you? The simple implication is you are not forced to escape characters in your regexp and replacement part. Consider you want to replace part of a unix/linux path string: /home/myuser/Desktop/mydirectory1/myfile.log if you use the default “/” you MUST escape all the “/” in your string:

sed 's/\/home\/myuser\/Desktop\/mydirectory1\/myfile.log/\/home\/user\/Desktop\/mydirectory2\/myfile.log/g' test.log

versus the simpler and more readable version with “#”

sed 's#/home/myuser/Desktop/mydirectory1/myfile.log#/home/user/Desktop/mydirectory2/myfile.log#g' test.log

And consider you use an variable:

cat file.test | sed "s/\[version\]/${PKGVERSION}/g"

* additional explanations:

  • /g (or what ever character is used for delimiter like “@”, “:”, “~” and so on) is for “Apply the replacement to all matches to the regexp, not just the first.”
  • -i (used in some of the examples above) is for inline replacement – the file you add in the sed command will be modified and the replacement will be saved in the file (the default behavior is to show the modified output in the standard output – console output)

Leave a Reply

Your email address will not be published. Required fields are marked *