Stuber
Stuber

Reputation: 477

sed find and replace from left most character

sed appears to find and replace from right to left.

for example:

echo "a_b_c_d" | sed 's/.*\(_.*\)/\1/'

outputs

_d

but why doesn't

echo "a_b_c_d" | sed 's/^.*\(_.*\)/\1/'

or

echo "a_b_c_d" | sed 's/.*\(_.*$\)/\1/'

output

_b_c_d

since these do not output _b_c_d how should this be done?

How should sed be used to find on first character and not last character when performing a find and replace?

Upvotes: 0

Views: 462

Answers (1)

anubhava
anubhava

Reputation: 784918

.* is greedy pattern that matches longest possible substring before matching following pattern, _ in this case. So placing .* before _ makes it match longest possible match before matching last _ in your input.

since these do not output _b_c_d how should this be done?

echo "a_b_c_d" | sed 's/^[^_]*\(_.*$\)/\1/'

_b_c_d

Here [^_]* is negated bracket expression (called character class in modern regex flavors) that matches 0 or more of any character that is not _.

Upvotes: 1

Related Questions