J.Doe
J.Doe

Reputation: 1

How to replace white space between 2 strings using sed

How I can replace a single white space for underscore just between 2 strings like the example below, using sed:

xxx ccc vvv bbb        333  444  555
   ^   ^   ^   ^^^^^^^^   ^^   ^^   <--- spaces visualized for easier counting

Desired output:

xxx_ccc_vvv_bbb        333  444  555

Upvotes: 0

Views: 2054

Answers (1)

Byte Commander
Byte Commander

Reputation: 6736

That's easy, you just do a global (g) replace (s) of single whitespace characters (\s) surrounded by word boundaries (\b) with underscores (_):

sed 's/\b\s\b/_/g'

Your example could be run like this:

echo "xxx ccc vvv bbb        333  444  555" | sed 's/\b\s\b/_/g'  

which produces the output you want:

xxx_ccc_vvv_bbb        333  444  555

Upvotes: 3

Related Questions