algorithmicCoder
algorithmicCoder

Reputation: 6799

Search and replace with sed when dots and underscores are present

How do I replace foo. with foo_ with sed simply running

sed 's/foo./foo_/g' file.php

doesn't work.

Upvotes: 40

Views: 108713

Answers (5)

Paul S
Paul S

Reputation: 1444

Interestingly, if you want to search for and replace just the dot, you have to put the dot in a character set. Escaping just the dot alone in a sed command for some reason doesn't work. The dot is still expanded to a single character wild card.

bash --version  # Ubuntu Lucid (10.04)

GNU bash, version 4.1.5(1)-release (x86_64-pc-linux-gnu)

Replaces all characters with dash:

echo aa.bb.cc | sed s/\./-/g
# --------

Replaces the dots with a dash:

echo aa.bb.cc | sed s/[.]/-/g
# aa-bb-cc

With the addition of leading characters in the search, the escape works.

echo foo. | sed s/foo\./foo_/g  # works
# foo_

Putting the dot in a character set of course also works.

echo foo. | sed s/foo[.]/foo_/g  # also works
# foo_

Upvotes: 23

rid
rid

Reputation: 63580

Escape the .:

sed 's/foo\./foo_/g' file.php

Example:

~$ cat test.txt 
foo.bar
~$ sed 's/foo\./foo_/g' test.txt 
foo_bar

Upvotes: 54

jfg956
jfg956

Reputation: 16758

For myself, sed 's/foo\./foo_/g' is working. But you can also try:

sed -e 's/foo\./foo_/g'

and

sed -e "s/foo\\./foo_/g"

and

sed 's/foo[.]/foo_/g'

Upvotes: 0

sashang
sashang

Reputation: 12234

Escape the dot with a \

sed 's/foo\./foo_/g' file.php

If you find the combination of / and \ confusing you can use another 'separator' character

sed 's#foo\.#foo_#g

The 2nd character after the s can be anything and sed will use that character as a separator.

Upvotes: 9

August Karlstrom
August Karlstrom

Reputation: 11377

You need to escape the dot - an unescaped dot will match any character after foo.

sed 's/foo\./foo_/g'

Upvotes: 6

Related Questions