kozner
kozner

Reputation: 141

why is this simple regex not working

i'm brushing up on my regex, seeing what i can do and also narrowing my standard coding style in it. then i wrote a small snippet that should've worked, but won't. so i kept reducing it to the most basic form, and still not doing i want it to do:

echo "a" | sed -e 's/a+/A/g'

why does it not output

A

i'm just bewildered why this doesn't work...

Upvotes: 0

Views: 67

Answers (2)

ebo
ebo

Reputation: 2747

If you want it to work with this syntax you need to make sure sed interprets the regular expression as an extended regular expression.

To do this you can use the -E on Mac OSX:

echo "a" | sed -E -e 's/a+/A/g'

or the -r flag on linux:

echo "a" | sed -r -e 's/a+/A/g'

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 157967

You don't need the +. If you want to replace every lowercased a by an uppercased A you can use this:

echo "abcdabdbda" | sed 's/a/A/g'

Output:

AbcdAbdbdA

The + is a special character in a regex. It matches the preceding character or group at least one or multiple times. You don't need it here.

Note: If you use + in a standard sed regex pattern you would need to escape it: \+ to give it is special meaning. Without escaping it will be threatened like a literal +.

Upvotes: 1

Related Questions