1

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.

1
  • 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.
    – MikeD
    Mar 28 '17 at 19:43
3

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)
1
  • Thank you, \1 was very helpfull
    – EHM
    Sep 16 '20 at 7:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.