如何使用sed在字符串中将逗号替换为“\”

时间:2021-01-10 16:49:50

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.

我有一个字符串,我需要使用shell脚本将“,”替换为“\”。我以为我可以用sed做这个但没有运气。

2 个解决方案

#1


You can do that without sed:

你可以不用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

#2


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

#1


You can do that without sed:

你可以不用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

#2


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