professorswag123 professorswag123 - 1 year ago 128
Bash Question

Linux sed command - using variable with backslash

I'm trying to replace a string in a file. i have to use a variable since i have to do this in alot of lines. how do i escape the backslash?


1234567#Hello World#Hello I\u0027m Scott


FOLDERID=`cat text.txt | cut -d# -f1` # example: 12345
oldstring=`cat text.txt | cut -d# -f2` # example: "Hello World"
newstring=`cat text.txt | cut -d# -f3` # example: "Hello I\u0027m Scott"
sed -i "s/${oldstring}/${newstring}/g" $FOLDERID/myfile.txt

cat myfile.txt after sed

Hello I0027m Scott

how can i escape a backslash? i only know how to escape slashes which would work like:

newstring=Hello I/u0027m Scott
echo ${newstring} # => Hello I\/u0027m Scott

Answer Source

Try this:

cd /tmp
mkdir -p 1234567
echo Hello World >1234567/myfile.txt
echo '1234567#Hello World#Hello I\u0027m Scott' >text.txt

Well, then:

IFS=\# read -r FOLDERID oldstring newstring <text.txt 
sed "s/${oldstring}/${newstring//\\/\\\\}/g" -i $FOLDERID/myfile.txt
cat 1234567/myfile.txt 
Hello I\u0027m Scott
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download