Reputation: 4352
I have a sample.txt file with contents as:
test sometest
test2 againsometext
My shell script uses sed to find the line which has "test" and replaces the whole line with "test google.com::100-ws sample.com::SAMPLE". sed fails with "unterminated `s' command".
#!/bin/sh
TEST1=test
TEST2=google.com::100-ws sample.com::GOLD-WS
echo $TEST1
echo $TEST2
if [[ ! -e sample.txt ]]; then
touch sample.txt
echo $TEST1 $TEST2 >> sample.txt
else
grep -q $TEST1 sample.txt
if [ $? -eq 0 ];then
sed -i 's/^$TEST1 .*$/$TEST1 '$TEST2'/' sample.txt
else
echo $TEST1 $TEST2 >> sample.txt
fi
fi
I have this same script in other places where the replacement text does not have any spaces and it works fine.
Can someone suggest some ideas to try?
TIA
Upvotes: 0
Views: 1476
Reputation: 2147
That space between test and msg is important. Otherwise you'll obliterate every line that begins with test. Also you can backrefence \1
your captured group \(test \)
https://regular-expressions.mobi/refcapture.html
#! /bin/bash
replace="google.com::100-ws sample.com::GOLD-W"
sed -i "s/^\(test \).*/\1$replace/" sample.txt
Upvotes: 1
Reputation: 22032
Assuming bash
is available in your environment, it will be just
enough to say:
#!/bin/bash
test1="test"
test2="google.com::100-ws sample.com::GOLD-W"
sed -i "s/^$test1.*/$test1 $test2/" sample.txt
sed
.Upvotes: 2