SED - confused by the s command.

echo "abc 123" | sed 's/[0-9]*/& &/g'
output:
 a b c  123 123

Why there are spaces between the "abc" letters?

echo "abc 123" | sed 's/[0-9]*/&&/'
output:
abc 123

Why the regex in the above script does not match anything? I thought [0-9]* should match 123 in any case.

---------- Post updated at 08:25 AM ---------- Previous update was at 08:17 AM ----------

ok, for the second question, I figured it out.
it is because sed tries to match the first character and it finds it does not match the input string and it stops further attempt because there's no "g" at the end of the pattern(no global search is needed).

[0-9]* means 0 or more occurrence.

to match 123 u have to write [0-9]+ or [0-9][0-9]* means 1 or more occurrence.

1 Like

As ROHON said:

What happen when check ing "a" :
does in match 0 or more occurrence of [0-9] ?
answer : yes, it matches 0 occurrence of [0-9] ...

you should go for the [0-9][0-9]* instead
...or, if your sed version can support extended character set for the regular expression, you can then use [0-9]+

1 Like

Thank you R0H0N and ctsgnb,
My understanding was wrong.
With your clarification, I understand it now, Thank you.