Question

With the help of SO I have been able to correct my sed command so I can use variables (was using ' instead of " and wasn't using g for global).

However, I am struggling to get the command to work correctly.

To give you some context, I have a file containing numerous lines of text and some line contain one or more tags. these tags are in the following format:

[#$key#] - i.e #[#] is used to indicate the presence of a key

Then I have an internal array object which stores a string value which contains each key and a corresponding value in the following format:

$key=$value

What I am trying to do is to cat my file containing the tags at the same time as using a global sed replace to swap the $key for the corresponding value within the array object.

The problem I have is that my grep/sed command is not replacing any of the text and I can't figure out why.

here is my code:

for x in "${prop[@]}"
do
     key=`echo "${x}" | cut -d '=' -f 1`
     value=`echo "${x}" | cut -d '=' -f 2`


    # global replace on the $MY_FILE
    cat $MY_FILE | sed "s|\[#${key}#\]|${value}|g" > ${TEMP_MY_FILE}
    cat $TEMP_MY_FILE > $MY_FILE

 done

I thought about using sed -i, but my version doesn't seem to support-i

Was it helpful?

Solution

Although [ doesn't have any special meaning in a double-quoted bash string, \[ still evaluates to [ since backslashes are processed to allow for escaping dollar signs. Try

sed "s|\\[#${key}#\\]|${value}|g"

as your sed command. The double backslash will causes a literal backslash to be sent to sed, which will use it to escape the [ to treat it literally as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top