0

I want to change one of its lines by sed but at the end of that line there is a backslash:

Some Text that should be changed \

I Used:

sed -i "s/$line/$newline/" $MyFile

sed says:

sed: -e expression #1, char 44: unknown option to `s'
sed: -e expression #1, char 84: unterminated `s' command
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Behnam Safari
  • 2,941
  • 6
  • 27
  • 42

3 Answers3

3

You need to first escape the string you're using inside the sed command, with something like:

line=$(echo $line | sed 's/\\/\\\\/g')

This will turn it from:

Some Text that should be changed \

into:

Some Text that should be changed \\

which will stop it from escaping the final delimiter.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
3

Given that you have:

line="Some Text that should be changed \\"

so your echo "$line" yields:

Some Text that should be changed \

Then sed sees:

sed -i "s/Some Text that should be changed \/Your replacement/" yourfile

and the backslash means that your search pattern hasn't ended, and therefore the substitute command is malformed - as the error message says.

You will have to get a second backslash onto the end of the string. One of a myriad ways of doing that is:

case "$line" in
(*\\)  line="$line\\";;
esac

This is just being inventive...but it has the merit of not executing any external command to fix the string. There are also more direct substitutions available in bash.

Now you can do:

sed -i "s/^$line$/$newline/" $myFile

and as long as $newline contains neither any slashes nor any backslashes, you will be safe enough.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1

One probable cause is that your $line or $newline contains the delimiter /.

Please try some other delimiters that do not occur in your patterns.

E.g.

sed -i "s@$line@$newline@" $MyFile
sed -i "s#$line#$newline#" $MyFile

-- edit according to @paxdiablo's comments.

The variable name $line misleads. It should be a pattern instead.

So you must make sure it's a valid pattern, in which a backslash \ should be escaped with \\

Ade YU
  • 2,292
  • 3
  • 18
  • 28
  • 1
    Actually, I'm not sure a delimiter change will help here because the string being used, `$line`, ends with `\` - that means it will escape _any_ delimiter. – paxdiablo Feb 23 '12 at 06:47
  • @paxdiablo You are right. The variable name `$line` misleads. It should be a `$pattern` instead. – Ade YU Feb 23 '12 at 06:53