使用sed或python将所有反斜杠替换为正斜杠

-1 投票
3 回答
802 浏览
提问于 2025-04-18 16:29

目标:把所有的反斜杠替换成正斜杠。

实际字符串:\\test.abc.com\path1\path1_1\123\ubntu

期望字符串://test.abc.com/path1/path1_1/123/ubntu

想用sed来处理这个问题,但感觉挺麻烦的。

有没有什么想法?

编辑:在Jenkins中读取环境变量

完整的使用场景是:这些路径通过Jenkins作为Windows UNC路径传递,需要在Unix上挂载。

在Python中使用*nix系统时

当通过变量尝试时,它的表现不一样!当我通过Python读取这些变量时,反斜杠会被解释器去掉。我尝试了用repr(variable)结合.decode('string_escape'),但没有成功。

在Unix上,raw_input()对Python没有帮助。

这是主要的Python脚本,叫做test1.py:

s=re.sub(r'\',r'/',repr(sys.argv[1].decode('string_escape'))),

这个脚本是这样运行的:

python test1.py \test.abc.com\path1\path1_1\123\ubntu

输出结果是:

//test.abc.compath1path1_1123ubntu;

为什么Python认为反斜杠不能显示呢 :-(

现在尝试通过环境变量用sed来处理。

3 个回答

0

通过sed这个工具,

$ sed 's~\\~/~g' file
//test.abc.com/path1/path1_1/123/ubntu

通过Python这个编程语言,

>>> import re
>>> s = r'\\test.abc.com\path1\path1_1\123\ubntu'
>>> print s
\\test.abc.com\path1\path1_1\123\ubntu
>>> m = re.sub(r'\\', r'/', s)
>>> print m
//test.abc.com/path1/path1_1/123/ubntu
2

你可以使用其他工具,但转换字符的工作就是 tr 这个命令的用途:

$ tr '\\' '/' < file
//test.abc.com/path1/path1_1/123/ubntu
1

更新了环境变量的内容。

你提到路径在一个环境变量里(我们假设叫做 UNC_PATH),那么在 Python 中可以这样写:

# test.py
import re, sys

s = re.sub(r'\\', r'/', sys.argv[1])
print s

然后这样调用它:

$ UNC_PATH=\\\\test.abc.com\\path1\\path1_1\\123\\ubntu
$ python test.py $UNC_PATH
//test.abc.com/path1/path1_1/123/ubntu

如果用 sed,可以这样做:

$ echo $UNC_PATH | sed -e 's/\\/\//g'
//test.abc.com/path1/path1_1/123/ubntu

原始回答

使用 sed 的话:

$ echo '\\test.abc.com\path1\path1_1\123\ubntu' | sed -e 's/\\/\//g' 
//test.abc.com/path1/path1_1/123/ubntu

在 Python 中:

>>> import re
>>> s = re.sub(r'\\', r'/', r'\\test.abc.com\path1\path1_1\123\ubntu')
>>> print s
//test.abc.com/path1/path1_1/123/ubntu

撰写回答