Home > Blockchain >  Not able to add a line of text after pattern using sed in OSX
Not able to add a line of text after pattern using sed in OSX

Time:09-21

I'm trying to add a line in a file afile.xyz using my script. This is what I've done so far using sed:

n="$(grep ".method" "$m" | grep "onCreate(Landroid/os/Bundle;)V")"

sed -i '' -e '/$n/ a\
"test", /Users/username/Documents/afile.xyz

I'm getting the error:

"onCreate\(\Landroid\/ ...": bad flag in substitute command: 'g'

How do I solve this? Please do help. Thanks.

Edit: Content of n

method protected onCreate(Landroid/os/Bundle;)V

CodePudding user response:

2 problems:

  1. because the sed body is in single quotes, the variable $n will not be expanded,
  2. the regular expression in $n contains the / dilimiters.

Try this:

n=$(...)
nn=${n//\//\\/}    # escape all slashes

sed -i '' '/'"${nn}"'/ a ...

The single-quoted sed body is interrupted to append the double quoted shell variable.

CodePudding user response:

You can also use a different delimiter for the RE:


sed -i '' -e "\#$n# a\\
\"test\"" /Users/username/Documents/afile.xyz
  • Related