user1164061
user1164061

Reputation: 4352

sed find and replace fails when string has a space in it

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

Answers (2)

Doyousketch2
Doyousketch2

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

tshiono
tshiono

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
  • 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.

Upvotes: 2

Related Questions