Stuart Campbell
Stuart Campbell

Reputation: 1147

Bash sed muti word find and replace

I am getting the error "unterminated substitute pattern" on mac os when attempting to replace multiple words with a different set of multiple words separated by spaces. I am doing this in a bash script. Reading from csv to replace a set of strings in files.

example

while IFS=, read col1 col2 col3

#$col1=FOO BAR
#$col2=another set of words
#$col3=file

do
   REGX="'s|$col2|$col3|g'"
   sed -i -e $REGX $col1
done < $config_file

I want the output to be "another set of words" can't seem to find out how to allow the spaces in the expression.

Thanks

Upvotes: 0

Views: 118

Answers (2)

fedorqui
fedorqui

Reputation: 289555

You are defining the substitution to do in a variable so that you use later on:

REGX="'s|$col2|$col3|g'"
sed -i -e REGX col3

Another example:

$ cat a
hello this is a test
$ REGX="s/this/that/g"
$ sed $REGX a
hello that is a test

However, I would directly use the command as follows:

while IFS=, read -r col1 col2 col3
do
   sed -i.bak -e "s|$col2|$col3|g" $col1
done < $config_file

Notes:

  • Use -r in read to avoid weird situations on corner cases.
  • Use double quotes in sed so that the variables within the expression are evaluated. Otherwise, it will look for literal $col2 and change with literal $col3.
  • Use -i.bak to create backup files when using -i. Otherwise, if you try and fail... you will lose your original document.

Upvotes: 1

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed -i "s#foo bar#another set of words#g"
# OR
sed -i "s#foo|bar#another string#g"

sed use | as regex OR, use another separator (the default / suite well here also)

Upvotes: 0

Related Questions