Tejender Mohan
Tejender Mohan

Reputation: 45

RegEx with Back Reference-Unix

I am executing below commands on Bourne shell but getting some unexpected error.

$ echo abcd 123 | grep --color '[a-z]*'

Output(abcd is colored) : abcd 123

$ echo abcd 123 | sed 's/\([a-z]*\)/\1/'

Output : abcd 123

shouldn't the result of 2nd command be abcd only ?

Upvotes: 2

Views: 38

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

No, because \([a-z]*\) captures the abcd part and the \1 backreference reinserts it back.

To remove the rest of the string use .* after the capturing group:

echo abcd 123 | sed 's/\([a-z]*\).*/\1/'

If the letters come at the beginning of the string, add a ^ at the pattern start.

Here is a Bash Ideone demo

Upvotes: 1

Related Questions