Yunyu L.
Yunyu L.

Reputation: 755

Replace with multiple spaces starting a string with sed

I have the input in /etc/hosts:

127.0.0.1 fake.hostname.net   fake

I want to replace the second fake with real. The following sed statement attempts to filter the two apart by matching two spaces before, but it does nothing:

sed -i -e 's/  fake/  new/g' /etc/hosts

Result is:

127.0.0.1 fake.hostname.net   fake

Expected result is:

127.0.0.1 fake.hostname.net   new

I have also tried the following with the same results:

sed -i -e 's/\s\sfake/\s\snew/g' /etc/hosts

Why does this happen, and what can I do to fix it? I am running Ubuntu 14.04.1 Server. I do not wish to simply replace the second match, as I am expecting things like:

127.0.0.1 asdf.hostname.net   fake

as well, so the space matching is the only acceptable method.

echo "127.0.0.1 fake.hostname.net   fake" | sed -e 's/  fake/  new/g'

Returns the expected result, but the same statement does not write to the file. Simply not putting the extra spaces in the statement writes to the file, so it's not a filesystem permissions issue.

Upvotes: 0

Views: 325

Answers (1)

hek2mgl
hek2mgl

Reputation: 157927

It should be

sed -i 's/fake$/real$/' /etc/hosts

$ matches the end of the line. You don't need the g option since there is only one match per line.

Upvotes: 1

Related Questions