简体   繁体   English

有没有办法让 sed 匹配最大字符串?

[英]Is there a way to get sed to match the maximum string?

So I have a file that contains many instances of something like foo.所以我有一个文件,其中包含许多类似foo. , foo.. , foo... , and so on. , foo.. , foo...等等。 I would like to replace them all with bar .我想用bar替换它们。

The command I used was sed -i 's/foo\.+/bar/g' abc.c .我使用的命令是sed -i 's/foo\.+/bar/g' abc.c However, it seems like sed only matches the minimal string, so foo.. is replaced by bar.但是,似乎 sed 只匹配最小字符串,所以foo..bar. , foo... with bar.. and so on. , foo...bar..等等。

Is there a way to get sed to do what I want?有没有办法让 sed 做我想做的事?

Of the 4 proposals in the comments, only half are correct, as follows:评论中的4个提议,只有一半是正确的,具体如下:

Mac_3.2.57$cat abc.txt 
0: foo
1: ifoo.
2: foo..
3: foo...
x: blah
inf: foo.........
Mac_3.2.57$#wrong-- matches "foo" followed by 0 or more "."s
Mac_3.2.57$sed 's/foo\.*/bar/g' abc.txt
0: bar
1: ibar
2: bar
3: bar
x: blah
inf: bar
Mac_3.2.57$#right-- matches "foo" followed by 1 or more "."s
Mac_3.2.57$sed -E 's/foo\.+/bar/g' abc.txt
0: foo
1: ibar
2: bar
3: bar
x: blah
inf: bar
Mac_3.2.57$#wrong-- matches "foo.+"
Mac_3.2.57$sed 's/foo\.\+/bar/g' abc.txt
0: foo
1: ifoo.
2: foo..
3: foo...
x: blah
inf: foo.........
Mac_3.2.57$#right-- matches "foo" followed by 1 or more "."s
Mac_3.2.57$sed -E 's/foo\.{1,}/bar/g' abc.txt
0: foo
1: ibar
2: bar
3: bar
x: blah
inf: bar

I would use what I consider the simplest: sed 's/foo..*/bar/g' abc.txt我会使用我认为最简单的: sed 's/foo..*/bar/g' abc.txt

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

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