Search code examples
regexlinuxbashsedcapturing-group

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?


Solution

  • 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