Seapoe
Seapoe

Reputation: 479

Find and Replace Specific characters in a variable with sed

Problem: I have a variable with characters I'd like to prepend another character to within the same string stored in a variable

Ex. "[blahblahblah]" ---> "\[blahblahblah\]"

Current Solution: Currently I accomplish what I want with two steps, each step attacking one bracket

Ex.

temp=[blahblahblah]
firstEscaped=$(echo $temp | sed s#'\['#'\\['#g)
fullyEscaped=$(echo $firstEscaped | sed s#'\]'#'\\]'#g)

This gives me the result I want but I feel like I can accomplish this in one line using capturing groups. I've just had no luck and I'm getting burnt out. Most examples I come across involve wanting to extract the text between brackets instead of what I'm trying to do. This is my latest attempt to no avail. Any ideas?

Upvotes: 0

Views: 2356

Answers (2)

CWLiu
CWLiu

Reputation: 4043

$ temp=[blahblahblah]    
$ fully=$(echo "$temp" |sed 's/\[\|\]/\\&/g'); echo "$fully"
\[blahblahblah\]

Brief explanation,

  • \[\|\]: target to substitute '[' or ']', and for '[', ']', and '|' need to be escaped.
  • &: the character & to refer to the pattern which matched, and mind that it also needs to be escaped.

As @Gordon Davisson's suggestion, you may also use bracket expression to avoid the extended format regex,

sed 's/[][]/\\&/g'

Upvotes: 2

shellter
shellter

Reputation: 37268

There may be more efficient ways, (only 1 s/s/r/ with a fancier reg-ex), but this works, given your sample input

fully=$(echo "$temp" | sed 's/\([[]\)/\\\1/;s/\([]]\)/\\\1/') ; echo "$fully"

output

\[blahblahblah\]

Note that it is quite OK to chain together multiple sed operations, separated by ; OR if in a sed script file, by blank lines.

Read about sed capture-groups using \(...\) pairs, and referencing them by number, i.e. \1.

IHTH

Upvotes: 3

Related Questions