linuxbashsed

Allowing input within sed command


I am attempting to make it so that within a file (rc.xml), it will replace between two strings (theme), and (this stuff), with the contents of a file openbox-$1 ($1 is an argument). Within sed, sed does absolutely nothing with the argument, and nothing is replaced. However, when I replace $1 with some predefined value, the script works as intended. However with that comes the loss of user input, which the whole purpose of the script (to set the proper Openbox settings for the user) is completely broken.

Current script:

#!/usr/bin/bash

# script is in testing so it copies a fresh copy
# of the file used in place of the test file
cp rccopy.xml rc.xml

# supposed to accept user input as $1 and write the
# contents of a file openbox-$1 between the two
# strings listed above
sed $'/ this stuff/ {r openbox-$1\n} ; /theme/,/ this stuff/ {d}' rc.xml > newfile

Modified sed command; works as intended but it can only copy over the file openbox-500

sed $'/ this stuff/ {r openbox-500\n} ; /theme/,/ this stuff/ {d}' rc.xml > newfile (

I have attempted to take away the singular quotes from sed, but it reports this without quotes:

sed: -e expression #1, char 2: unknown command: `/' ./replace.sh: line 3: /theme/,/: No such file or directory

With double quotes: sed: -e expression #1, char 0: unmatched `{'

What is expected is for sed to read $1 as an argument in its place (so $1 would be 500 for instance if the user inputs it), and for it to read the file openbox-500 (just as an example). From there, the script would (as mentioned earlier), replace whatever is between the two strings specified (strings are mentioned earlier) and write the changed file to newfile.


Solution

  • Dollar-quote strings aren't subject to variable expansion (see 3.1.2.4 ANSI-C Quoting). Do it like this

    sed "/ this stuff/ {r openbox-$1"$'\n'"} ; /theme/,/ this stuff/ {d}" rc.xml > newfile
    

    or put a literal line break there.