I would need to replace a string having spaces with another string in a file in a bash script where all calls should be done through a function that writes the command to a log file and then runs the command. The logrun function uses special character $@
for reading in the command. I'm trying to use sed for replacing but I can't find a way to escape spaces when the sed command having spaces in expression parameter goes through $@
.
I have simplified the problem to test scripts where I use sed for replacing a c with a b c.
test1.sh works great:
#!/bin/bash
TESTFILE=/tmp/test.txt
echo "a c" > $TESTFILE
sed -i -e 's/a c/a b c/' $TESTFILE
test2.sh fails:
#!/bin/bash
function logrun() {
CMD=$@
$CMD
}
TESTFILE=/tmp/test.txt
echo "a c" > $TESTFILE
logrun sed -i -e 's/a c/a b c/' $TESTFILE
Result:
sed: -e expression #1, char 3: unterminated `s' command
The reason for error is the space(s) in the -e expression. I haven't found a way to call sed through that function. I have tried to use double quotes instead of single quotes and to escape spaces with a backslash etc. I am really curious to find out what's the correct way to do it.