0

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.

2
  • can you confirm that the expression works as expected if you use cat: cat /etc/hosts | sed -e 's/ fake/ new/g'? also, confirm that the whitespace is, in fact, spaces, not tabs? Commented Mar 29, 2015 at 19:07
  • @WilliBallenthin It does: echo "127.0.0.1 fake.hostname.net fake" | sed -e 's/ fake/ new/g' and yes, it's spaces, not tabs. If I don't put the spaces in the expression, the file updates, so it's not a permissions issue. Stack Overflow is nuking the double space even in code formatting. Commented Mar 29, 2015 at 19:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

That solved my problem, thanks. I'm still wondering about the space behavior, however.
probably it was a tab?
I'm certain it was a space, even ran it through a hex dump.
This will replace fake in 127.0.0.1 fake but that might not cause any problems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.