robbbbbb
robbbbbb

Reputation: 147

Alternation not matching as expected in sed

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/foo.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

Upvotes: 3

Views: 1298

Answers (2)

sverre
sverre

Reputation: 6919

Escape the | or use extended regular expressions

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

Upvotes: 2

Mat
Mat

Reputation: 206699

Try escaping the alternation too:

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

Very related: Use of alternation in sed regex.

Upvotes: 4

Related Questions