Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace a comma to "\," in a string using sed

Tags:

shell

sed

I have a string in which I need to replace "," with "\," using shell script. I thought I can use sed to do this but no luck.

like image 232
user3920295 Avatar asked Feb 11 '23 06:02

user3920295


2 Answers

You can do that without sed:

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

To replace all occurrences of "," use this:

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

Example:

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

Output:

Hello\,World
like image 170
Jahid Avatar answered Feb 19 '23 13:02

Jahid


You need to escape the 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 string is on a file, you can use:

sed -i 's/,/\//g' myfile.txt
like image 32
Pedro Lobito Avatar answered Feb 19 '23 13:02

Pedro Lobito