I found line sed 's~ ~~g' in a shell script on a Linux system. What is this ~?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
It’s an alternative delimiter for the sed substitute (s) command. Usually, the slash is used, as in s/pattern/replacement/, but sed allows for almost any character to be used.
The main reason for using another delimiter than / in the sed substitution expression is when the expression will act on literal / characters.
For example, to substitute the path /some/path/here with /other/path/now, one may do
s//some/path/here//other/path/now/
This suffers from what’s usually referred to as “leaning toothpick syndrome”, which means it’s hard to read and to properly maintain.
Instead, we are allowed to use another expression delimiter:
s#/some/path/here#/other/path/now#
Using ~ is just another example of a valid substitution expression delimiter.
Your expression
s~ ~~g
is the same as
s/ //g
and will remove all spaces from the input. In this case, using another delimiter than / is not needed at all since neither pattern nor replacement contains /.
Another way of doing the same thing is
tr -d ' ' <infile >outfile
Method 2
It’s a substitution delimiter. The most often used delimiter is a forward slash /. But sed can use any character as a delimiter – it will automatically use the character following the s as a delimiter:
sed '<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4b784">[email protected]</a> @@g' sed 's+ ++g' sed 's \g' sed 's* **g'
Also it is possible to use space as delimiter:
echo "foo" | sed 's foo bar g'
Other delimiters than / are most often used when you have many slashes in your command in the syntax is getting confusing. Consider this case where we want to convert multiple spaces to just one space character: Instead of
echo " a b c " | sed 's/s{1,}/ /g'
you can run
echo " a b c " | sed 's~s{1,}~ ~g'
which is more clear.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0