Francisco Angel
Francisco Angel

Reputation: 13

Using sed to replace a number located between two other numbers

I need to replace a numeric value, that occurs in a specific line of a series of config files in a pattern like this:

string number_1 number_to_replace number_2

I want to obtain something like this:

string number_1 number_replaced number_2

The difficulties I encountered are:

The closest attempt I got until now is:

echo "field 4 4 4" | sed 's/\s4\s/3/'

Which ouputs:

field34 4

This is close, given that I want to replace the intermediate number I added another "\s" to try to use the known fact that the line starts with a character.

echo "field 4 4 4" | sed 's/\s\s4\s/3/'

Which gives:

field 4 4 4

So, nothing is replaced this time. How can I proceed? A somewhat detailed explanation would be ideal, because my knowledge of replacing expressions that involve patterns in nearly zero. Thanks.

Upvotes: 1

Views: 36

Answers (1)

Inian
Inian

Reputation: 85530

You can do something like below, which matches your exact sequence of digits as in the example. You could replace 3 with any digit of your choice.

sed 's/\([0-9]\{1,\}\)[[:space:]]\([0-9]\{1,\}\)[[:space:]]\([0-9]\{1,\}\)/\1 3 \3/'

Notice that I've used the POSIX bracket expression to match the whitespace character which should be supported in any variant of sed you are using. Note that \s is supported in only the GNU variants.

The literal meaning of the regex definition is to match a single digit followed by a space, then a digit and space and another digit. The captured groups are stored from \1. Since your intention is to remove the 2nd digit, you replace that with the word of your choice.

If the extra escapes causes it unreadable, use the -E flag for extended regex support. I've used the default BRE version

Upvotes: 1

Related Questions