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

时间:2015-05-04 02:38:58

标签: shell sed

我有一个字符串,我需要使用shell脚本将“,”替换为“\”。我以为我可以用 ` cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); jTextField3.setText(""+secretKeySpec); String cleartextFile = "E:\\"+dir; FileInputStream fis = new FileInputStream(cleartextFile); CipherInputStream cis = new CipherInputStream(fis, cipher); FileOutputStream fos = new FileOutputStream("E:\\d"+dir); FileChannel out = fos.getChannel(); out.transferFrom(Channels.newChannel(cis), 0, Long.MAX_VALUE); ` 来做这件事,但没有运气。

2 个答案:

答案 0 :(得分:4)

您可以在没有sed的情况下执行此操作:

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

替换所有出现的","用这个:

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

示例:

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

输出:

Hello\,World

答案 1 :(得分:2)

你需要逃避反斜杠\/
我不确定你的输入是什么,但这样可行:

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

输出:

teste\test

演示: http://ideone.com/JUTp1X

如果字符串在文件上,您可以使用:

sed -i 's/,/\//g' myfile.txt
相关问题