sed regex with '+' doesn't work - why?

I don't understand it. I'd like to replace the ip-up 9490:notify_rc string to ip-up ****:notify_rc. I thought it's simple:

echo "ip-up 9490:notify_rc" | sed -e 's/ip-up [0-9]+:notify_rc/ip-up ****:notify_rc/'

but no, it doesn't work for me, the output is ip-up 9490:notify_rc. Why? How can I do it?

Instead of [0-9]+ I've tried: \S+ [:num:]+ etc., tried to add -r switch to sed command, without success. The result is the original string every time.

If I change + to *, then it becomes working; but what's wrong with plus sign?

Update
Here is a short sample:

echo "ip-up 9490:notify_rc" | sed -e 's/ip-up [0-9]+:notify_rc/ip-up ****:notify_rc/'
ip-up 9490:notify_rc
echo "ip-up 9490:notify_rc" | sed -e 's/ip-up [0-9]+:notify_rc/ip-up ****:notify_rc/' -r
ip-up 9490:notify_rc
echo "ip-up 9490:notify_rc" | sed -e 's/ip-up [0-9]+:notify_rc/ip-up ****:notify_rc/' -E
ip-up 9490:notify_rc
sed --version
sed (GNU sed) 4.2.2
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Jay Fenlason, Tom Lord, Ken Pizzini,
and Paolo Bonzini.
GNU sed home page: <
General help using GNU software: <
E-mail bug reports to: <>.
Be sure to include the word ``sed'' somewhere in the ``Subject:'' field.
0

3 Answers

Don't put anything (except the sed script) after the -e switch.

$ echo "ip-up 9490:notify_rc" | sed -r -e 's/ip-up [0-9]+:notify_rc/ip-up ****:notify_rc/'
ip-up ****:notify_rc
1

You're hitting the difference between regular expression and extended regular expression.

The one or more operator is + in extended regular expression. You can tell sed that the regex is an extended one using the option -r or -E.

echo "ip-up 9490:notify_rc" | sed -r -e 's/ip-up [0-9]+:notify_rc/ip-up ****:notify_rc/'

If you use (basic) regular expression, you need to escape that operator such it is not taken as a character.

echo "ip-up 9490:notify_rc" | sed -e 's/ip-up [0-9]\+:notify_rc/ip-up ****:notify_rc/'
3

If there are no ohter numbers in the string to preserve you can use the following syntax:

sed -e "s/[0-9]/\*/g"

This will replace any number with an asterisk.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like