Michael
Michael

Reputation: 87

Regular Expression (Replace) only first match

I am trying to cut (replace) a string with regular Expression (sed) but want to match the first occurence. In Result you can see it stops ever at the third DATA.

Text:

Cool Text Cool Text DATA : first text DATA : second text DATA : third text

Regular Expression:

sed 's/.*DATA//'

Result:

 : third text

Upvotes: 2

Views: 236

Answers (3)

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed 's/DATA\(.*\)/&#\1/;s/.*DATA\(.*\)#\1/\1/' YourFile

Sed always try to take the biggest pattern, so in your problem, it take all until last DATA (biggest possible). I just use the reverse construction by keeping the biggest.

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247202

If you can switch to perl, you can use a non-greedy quantifier:

echo "$string" | perl -pe 's/.*?DATA//'
# .............................^

That will stop at the first DATA

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

With sed, you can use the trick of the placeholder:

sed  's/DATA/###/;s/.*###//;'

With gnu grep, you can use a lookbehind in perl mode:

grep -Po '(?<=DATA).*'

Upvotes: 5

Related Questions