简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM