0

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

user1164061
  • 4,222
  • 13
  • 48
  • 74
  • 1
    `sh` ([Bourne-shell](https://en.wikipedia.org/wiki/Bourne_shell)) is usally not `bash` ([Bourne-again shell](https://en.wikipedia.org/wiki/Bash_(Unix_shell))). – Cyrus Dec 02 '20 at 01:10
  • 1
    Please paste your script first at [shellcheck.net](http://www.shellcheck.net/) and try to implement the recommendations made there. – Cyrus Dec 02 '20 at 01:10
  • 1
    Why do you have those single quotes around `$TEST2`? What do you want the output to look like? – Beta Dec 02 '20 at 01:14
  • Does this answer your question? [When to wrap quotes around a shell variable?](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) Briefly, `if grep -q "$TEST1" sample.txt; then sed -i "s/^$TEST1 .*\$/$TEST1 $TEST2/" sample.txt` (note also [Why is testing “$?” to see if a command succeeded or not, an anti-pattern?](https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern)) – tripleee Dec 02 '20 at 05:04

2 Answers2

1

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
  • You need to quote strings which contain blank character(s) to prevent word-splitting.
  • It is not a good practice to use uppercase alphabets for normal variable names.
  • You need to use not single quotes but double quotes to enable variable expansion as a command to sed.
tshiono
  • 21,248
  • 2
  • 14
  • 22
  • This works. Thank you! I used upper case cos they are actually env variables. I changed name cos I cant share the real name. – user1164061 Dec 02 '20 at 21:30
  • Thank you for the feedback. I've understood why you picked uppercase variable names. – tshiono Dec 02 '20 at 21:38
1

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
Doyousketch2
  • 2,060
  • 1
  • 11
  • 11