Gil
Gil

Reputation: 1538

Sed to match the first of the recurring character

My regex for displaying everthing after "(" :

 echo "apples (orange) (plum)" | sed -re 's/^.+\(//' 

Output : plum)

Expected output :orange) (plum)

How can I catch the first occuring character instead of the last ?

Upvotes: 0

Views: 223

Answers (2)

ormaaj
ormaaj

Reputation: 6577

Can't. .* and .+ are always greedy. There are other ways to accomplish this though.

Delete all leading non-('s

$ sed 's/[^(]*(//' <<<'apples (orange) (plum)'
orange) (plum)

Or almost equivalent and not really an improvement would be saving the second part using a group.

$ sed 's/[^(]*(\(.*\)$/\1/' <<<'apples (orange) (plum)'
orange) (plum)

Upvotes: 1

rush
rush

Reputation: 2564

echo "apples (orange) (plum)" | sed -re 's/^[^(]+\(//'

. matches any character, therefore sed watches the last bracket in the line. Therefore . mathes ( and ^[^(]+\( mathes apples (orange) (. So you need to use [^(]* to not match any ( at all as you suggest.

Upvotes: 1

Related Questions