开发者

Alternation not matching as expected in sed

开发者 https://www.devze.com 2023-03-10 04:06 出处:网络
Learning sed, I want to change the drive letter of the following input lines from \'a\' to \'d\': http:/a/foo/bar.txt

Learning sed, I want to change the drive letter of the following input lines from 'a' to 'd':

http:/a/foo/bar.txt
http:/a/bar/f开发者_JAVA百科oo.txt
file:/a/foobar.txt
http:/b/foo/bar.txt
http:/c/foobar.txt

I'm using the following sed expression:

sed 's_^\(http|file\):/a_\1:/d_' in.txt

That is: if a line starts with either 'http' or 'file' then follows with ':/a', capture the protocol as group 1, and replace the 'a' with a 'd'. Or at least it's supposed to be.

However, I can't seem to get the alternation operator '|' to work. If I just use 'http' or 'file' on it's own for the group, the command behaves as expected, if I use 'http|file' for the group, then none of the lines match:

mbook:sed rob$ sed 's_^\(http\):/a_\1:/d_' in.txt
http:/d/foo/bar.txt
http:/d/bar/foo.txt
file:/a/foobar.txt
http:/b/foo/bar.txt
http:/c/foobar.txt
mbook:sed rob$ sed 's_^\(file\):/a_\1:/d_' in.txt
http:/a/foo/bar.txt
http:/a/bar/foo.txt
file:/d/foobar.txt
http:/b/foo/bar.txt
http:/c/foobar.txt
mbook:sed rob$ sed 's_^\(http|file\):/a_\1:/d_' in.txt
http:/a/foo/bar.txt
http:/a/bar/foo.txt
file:/a/foobar.txt
http:/b/foo/bar.txt
http:/c/foobar.txt


Try escaping the alternation too:

sed 's_^\(http\|file\):/a_\1:/d_' in.txt

Very related: Use of alternation in sed regex.


Escape the | or use extended regular expressions

sed -r 's_^(http|file):/a_\1:/d_'
0

精彩评论

暂无评论...
验证码 换一张
取 消