Issue
sed with 'g' modifier not replacing all matches.
Example:
$ sed -e 's:foo\([^\s]*\):\1 :g' <(echo "hey foobar foobar ")
Expected:
"hey bar bar"
Actual:
"hey bar foobar"
What am I missing here?
Solution
\s
is a PCRE extension that POSIX sed
isn't guaranteed to implement; and without it being honored, your match stops only at the letter s
or at backslashes, not at spaces.
You get correct behavior if instead you use:
sed -re 's:foo([^[:space:]]*):\1 :g'
...or...
sed -e 's:foo\([^[:space:]]*\):\1 :g'
To better see what's going on for your self, you can change the replacement string to have sigils around it, to see exactly what is being captured:
$ sed -e 's:foo\([^\s]*\):<\1 >:g' <<<"hey foobar foobar "
hey <bar foobar >
$ sed -e 's:foo\([^\s]*\):<\1 >:g' <<<"hey foobar foobar s foobar foobar "
hey <bar foobar >s <bar foobar >
Answered By - Charles Duffy Answer Checked By - Mildred Charles (WPSolving Admin)