SED * operator

  1. echo "abc 123 abc" | sed 's/[a-z]*/X/'

yields -

X 123 abc

Does this mean the "*" operator matches ONLY the first and
the entire token - "abc" and replaces with "X" ?

  1. echo "123 abc" | sed 's/[a-z]*/X/'

yields -

X123 abc

What does this indicate about the "*" operator ??

Hi, I think it matches even before You get to the first character. [a-z]* means zero or more occurrences of any letter in the range a to z. And You have that whereever You search in any file. Sed stops when it has found a match. Maybe You were looking for something like

echo "abc 123 abc" | sed 's/[a-z]*/X/g'
or maybe even
echo "abc 123 abc" | sed 's/[a-z]/X/g'

where the g tells sed to continue searching for matches on the whole line.

/Lakris

It should match zero or more characters in the character class [a-z]
it will match 'a', 'b', 'c' and not the next space character <' '> so just that part is replaced by 'X'

Here the very first character is outside the range of [a-z] which means zero character(s) have been matched - hence replacing with 'X'

    • means zero or more character
  • dosnt match anything. its a quatifier, that menas, zero, or mroe

z* matchs
""
"z"
"zz"
"zzz"

Thanks to all for the replies.

To matrixmadhan :

Going by your reply -

"It should match zero or more characters in the character class [a-z]
it will match 'a', 'b', 'c' and not the next space character <' '> so just that part is replaced by 'X'"

I tried :-

echo "a 123 abc" | sed 's/[a-z]/X/'
echo "ab 123 abc" | sed 's/[a-z]
/X/'
echo "abc 123 abc" | sed 's/[a-z]*/X/'

all gave the same output as : X 123 abc

From your reply and the above result I understand - "*" will always start checking from the left in the input string. If it does not find a match , 'X' is replaced at the very beginning of the input string and the job is done.

But if it does find a match , it ends trying to find another match AND 'X' is kept in place of the matched token/characters.

Would request you to please confirm/correct the above.

Thanks

I hope you have added the quotes ( "" ) for explanatory purpose :slight_smile:

It will check from the start of the string ( <left of the string> ) and I hope this is what you meant, right?

Rest, you are right.

You need to remember this * means match zero or more characters.

There is going to be a definite replacement of zero or more matching characters.

yes, of course,
the only way to show it matches nothing ""