简体   繁体   English

替换为以sed开头的多个空格

[英]Replace with multiple spaces starting a string with sed

I have the input in /etc/hosts: 我在/ etc / hosts中有输入:

127.0.0.1 fake.hostname.net   fake

I want to replace the second fake with real . 我想用real代替第二个fake The following sed statement attempts to filter the two apart by matching two spaces before, but it does nothing: 下面的sed语句尝试通过匹配之前的两个空格来将两者分开,但是它什么也不做:

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. 我正在运行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. 您不需要g选项,因为每行只有一个匹配项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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