How to replace comma with "\" in a string using sed

I have a line where I need to replace "," with "\" using a shell script. I thought I could use it sed

for this, but no luck.

+3


source to share


2 answers


You can do it without sed

:

string="${string/,/\\,}"

      

To replace all occurrences of ",", use the following:

string="${string//,/\\,}"

      



Example:

#!/bin/bash
string="Hello,World"
string="${string/,/\\,}"
echo "$string"

      

Output:

Hello\,World

      

+2


source


You need to escape back slash \/


I'm not sure what your input is, but this will work:

echo "teste,test" |sed  's/,/\\/g'

      


output:

teste\test

      




Demo: http://ideone.com/JUTp1X


If the line is in a file, you can use:

sed -i 's/,/\//g' myfile.txt

      

+2


source







All Articles