Paul Dawson
Paul Dawson

Reputation: 1382

Sed prepend when searching for colon

I need to search for each instance of a colon ":" and then prepend a string to the word before that colon.

Example:

some data here word:number

Desired outcome:

some data here prepend_word:number

I've tried:

 sed "s/:/s/^/prepend_/g"

This adds prepend_ to the beginning of the line: prepend_some data here word:number

sed "s/:/prepend_&/g"

this adds prepend_ right before the colon: some data here wordprepend_:number

Upvotes: 2

Views: 47

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

You need to use

sed 's/[^[:space:]]*:/prepend_&/g'

The [^[:space:]]*: pattern searches for 0 or more non-whitespace chars and a : after them, and the prepend_& replacement pattern will replace the match with itself (see &) and insert prepend_ before it.

See an online sed demo:

sed 's/[^[:space:]]*:/prepend_&/g' <<< "some data here word:number more:here"

Output: some data here prepend_word:number prepend_more:here.

Upvotes: 2

Related Questions