Find and replace with sed using wildcard in both finding and replacing

5,610

Escape the ( and search for not ). Use \1 to keep the matched grouping.

sed 's/a\(([^)]*\))/a\1_mynewstring)/g' file1

Gives:

a(bc_mynewstring)
a(l_mynewstring)
a(d_mynewstring)
a(loke_mynewstring)
a(babab_mynewstring)
a(h323_mynewstring)
Share:
5,610

Related videos on Youtube

knishs_bankroll
Author by

knishs_bankroll

Updated on September 18, 2022

Comments

  • knishs_bankroll
    knishs_bankroll over 1 year

    So I understand how to use sed, namely when searching using wildcards, .*. The problem I am facing is how to find and the replace using the wildcard both times, in both the search and replace portions of the command. An example will help to better illustrate this:

    $cat test.txt
    a(bc)
    a(l)
    a(d)
    a(loke)
    a(babab)
    a(h323)
    $
    

    I want to append a string, _mynewstring, to whatever comes after a([string of some length]. Please note that I cannot simply do a find and replace of the closing parenthesis because there are other closing parenthesis in each line (which I leave out for ease of example), but none whose paired opening parenthesis has an a in front of it. The output should look like:

    $cat test.txt
    a(bc_mynewstring)
    a(l_mynewstring)
    a(d_mynewstring)
    a(loke_mynewstring)
    a(babab_mynewstring)
    a(h323_mynewstring)
    $
    

    I have tried the following,

    sed -i 's/a(.*)/a(.*_mynewstring)/g' test.txt
    

    but this just outputs,

    cat test.txt
    a(.*_mynewstring)
    a(.*_mynewstring)
    a(.*_mynewstring)
    a(.*_mynewstring)
    a(.*_mynewstring)
    a(.*_mynewstring)
    

    Clearly the wildcard is being taken as a literal string, which is not what I need but after exhaustive Googling I am not sure how I would do it otherwise. I have attempted solutions using awk, grep, and combinations of all three to no avail. Thanks for any help you can provide.

    • MikeD
      MikeD about 7 years
      You need to use -r option for regular expressions. You would use \1 in the replace portion to correspond to the first item matched within parentheses.
  • EHM
    EHM over 3 years
    Thank you, \1 was very helpfull