簡體   English   中英

使用sed或python將所有反斜杠替換為正斜杠

[英]To replace all backslashes with forward slashes using sed or python

目標:用正斜杠替換所有反斜杠。

實際字符串:\\\\ test.abc.com \\ path1 \\ path1_1 \\ 123 \\ ubntu

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

試圖讓sed滿足上述要求已成為一項艱巨的任務

有什么想法嗎?

編輯:在Jenkins中讀取為Env變量 完整的用例是:它們通過jenkins作為Windows UNC路徑傳遞,需要在Unix上安裝

在* nix上的Python中

通過變量嘗試時,其行為會有所不同!,當我通過python讀取變量時,解釋器將'\\'字符串切掉。 我曾嘗試與.decode('string_escape')結合使用repr(variable),但無濟於事。 raw_input()在Unix上的python中無濟於事

這是主要的名為test1.py的python腳本

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不能顯示'\\':-( –

現在嘗試通過env變量通過sed進行操作。

您可以使用其他工具,但轉換的字符是工作tr是為創建:

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

更新了環境變量。

您說路徑在環境變量中(假設為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

通過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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM