How to escape % with sed?

Hello,
I am running ubuntu 16.04
I searched "how to replace dot by % using sed " but no luck.

file

My.Name.Is.Earl

Expected output

My%Name%Is%Earl

I tried:

sed -i "s|.|[%]|g" file
sed -i "s|.|{%}|g" file
sed -i "s|.|\%|g" file

I'd appreciate your help

Thank you
Boris

Hello baris35,

Could you please try following.

sed 's/\./%/g'  Input_file

Thanks,
R. Singh

1 Like

To add: in regular expressions, a . (dot) has a special meaning as it stands for "any character" . In order to change the meaning to a literal dot, it can be escaped with a \ character (backslash) preceding the dot. The % -sign is not a special character here and therefore does not need to be escaped.

1 Like
tr '.' '%' < file

I focused on % symbol and missed dot to be escaped but I do not remember that I was escaping it earlier.
Thank You All!

Hello Again,
I am accustomed to run sed without escaping the dot. I had not encountered any issue earlier.
Your solution works but could you please explain what is the difference between replacement of . by % and standard replacement as shown in given below example? Why do we escape dot ?

File1: (replacement of dot by percentage)

My.Name.Is.Earl

Working Solution:

sed 's/\./%/g'  File1

File2: (removal of .txt.doc extension)

Test1.test2.txt.doc

Expected:

Test1.test2

Solution:

sed -i "s|.txt.doc||g" File2

I have not escaped dot in example two.
Also works when we use rename command; without escaping dot, able to rename the file..

Thank you
Boris

The dot is a special character in regexes, a wildcard. man regex :

It also matches dots like in your example 2, but would also work on -txt-doc . To explicitly match a dot in the text, it has to be escaped innregexes to suppress its special meaning.

1 Like