Ksh: Replace backslash characters

Hi All,

I have a requirement to read a line from a file with some search string, replace any backslash characters in that line and store in a variable.

Shell script: replace.ksh

#!/bin/bash
file2=input.rtf
line=`grep "Invoice Number" ${file2} | head -1 | sed 's/\\//g'`
echo "start printing"
echo "line_number:${line}"

The Input file "input.rtf" has the following 3 lines:

whcjkwekcwn
\ab0\ai0\af1\afs18 \ltrch\fcs0 \b0\i0\f40\fs18\insrsid9709693\charrsid550304 Invoice Number:\cell }
asdagv

When I execute the script, I am getting following error:

$ replace.ksh
sed: command garbled: s/\//g
start printing
line_number:

My expectation is the line should be converted to

aab0aai0aaf1aafs18 altrchafcs0 ab0ai0af40afs18ainsrsid9709693acharrsid550304 Invoice Number:acell }

which is not happening.

Can someone please help me to solve this?

Thanks in advance.

prashas_d

The heading is ksh but you are using bash but try by adding one more slash in the sed...

#!/bin/bash
file2=input.rtf
line=`grep "Invoice Number" ${file2} | head -1 | sed 's/\\\//g'`
echo "start printing"
echo "line_number:${line}"

Try this,

#!/bin/bash
file2=input
line=`grep "Invoice Number" ${file2} | head -1 | sed 's/\\\/a/g'`
echo "start printing"
echo "line_number:${line}"

Interestingly, the alternative command substitution method works just fine with two slashes...

$ line=$(sed -n '/Invoice Number/ {s/\\//g;p;q;}' $file2)

$ echo $line
ab0ai0af1afs18 ltrchfcs0 b0i0f40fs18insrsid9709693charrsid550304 Invoice Number:cell }

@malcomex99,

Hey Thanks a lot. Keeping three backslashes is providing me the required output. :slight_smile:

As per my knowledge, to espace backslash, we need to keep one more backslash.

But why it is expecting to keep an additional backslash here again? Can you please explain if you dont mind?

Thanks,
prashas_d

Yes, at command line, a single backslash is enough to escape but in a script it differs.

That's not because it's in a script, that due to the double shell interpretation when using the archaic but still too much used backticks.

As scottn pointed out, using the alternative "$( ... )" syntax doesn't exhibit that issue (and many others).