使用 sed 后跟一个点 (.)

Substituting specific string using sed followed by a dot (.)

我正在对文件进行如下替换:

文件:abc.txt

`include foo.h

int main
{
int foo
foo and bar
barfoobar
}

我想替换大括号里面的'foo',但是我不想替换include指令里面写的'foo'。

我尝试使用:

sed -i "s/\bfoo\b/my_foo/g"

输出:

`include my_foo.h

int main
{
int my_foo
my_foo and bar
barfoobar
}

有什么建议吗??

试试这个:

sed -i "/^[^`]/ s/\bfoo\b/my_foo/g"

它的作用是"Only apply the substitution to lines whose first character is not ` (backtick)."

匹配后跟没有 .并且可以选择后跟行尾

sed  -E 's/foo[^.]?$/my_foo/g' test.txt   

它需要扩展正则表达式。 MacOS 上的 -E 或 linux (man sed) 上的 -r。

有正则表达式测试器,例如 http://www.regextester.com/,可以探索正则表达式,或者很多 IDE 都内置了它们。

例如Regex to match URL end-of-line or "/" character

sed '/include/b; s/foo/my_&/' foo
include foo.h

int main
{
int my_foo
}

这意味着,如果找到include,分支跳转到命令的末尾。

我相信这个命令就是您要找的:

如果要替换所有具有 foo 的行,但不包括具有 include

的行

sed -i '/foo/ {/include/! s/foo/my_foo/g}' test

或者 如果要替换 foo 的所有条目,但不包括具有 foo.

的条目

sed -i '/foo/ {/foo./! s/foo/my_foo/g}' test

最后一行问题和标题好像有歧义,两种情况我都回答了​​。

Session 输出:

$ cat test
include foo.h

int main
{
int foo
}
$ 
$ sed -i '/foo/ {/foo./! s/foo/my_foo/g}' test
$ cat test
include foo.h

int main
{
int my_foo
}