2014-09-30 66 views
0

下面的命令在bash中正常運行。python中的bash:sed unterminated s命令

/folk/vlm/commandline/./vlmTool find -l all | grep -e "^Target ID" -e "City" -e "Zone" | sed "s#.*City.*#&\n#g" > new.txt 

但是在Python當我嘗試執行相同的命令,我得到:

['sed', 's#.*City.*#&\n#g'] 
**sed: -e expression #1, char 12: unterminated `s' command** 

代碼:

#!/usr/local/bin/python -tt 

import subprocess 
import shlex 
cmd = '/folk/vlm/commandline/./vlmTool find -l all | grep -e "^Target ID" -e "City" -e "Zone" | sed "s#.*City.*#&\n#g" > new.txt' 
cmd2= "/folk/vlm/commandline/./vlmTool find -l all" 
args1 = shlex.split(cmd2) 
cmd3 = 'grep -e "^Target ID" -e "City" -e "Zone"' 
args2 = shlex.split(cmd3) 
cmd4 = 'sed "s#.*City.*#&\n#g"' 
args3 = shlex.split(cmd4) 
print args3 
p1 = subprocess.Popen(args1, stdout=subprocess.PIPE) 
p2 = subprocess.Popen(args2, stdin=p1.stdout, stdout=subprocess.PIPE) 
p3 = subprocess.Popen(args3, stdin=p2.stdout, stdout=subprocess.PIPE) 
p1.stdout.close() 
p2.stdout.close() 
output = p3.communicate()[0] 
+1

嘗試'['sed',r's#。* City。*#&#n#g']''。 – SethMMorton 2014-09-30 17:25:38

回答

2

\n序列在蟒蛇理解爲一個轉義序列新隊;因此sed認爲你已完成s命令並開始新命令。以獲得反斜槓包含在字符串中,或​​者轉義它,如...\\n...或使用原始字符串:r's#.*City.*#&\n#g'

+0

謝謝... \\ n與所需的輸出一起工作,但使用r並沒有提供給我所需的結果。 – Punit 2014-09-30 21:27:52

+0

你是最棒的。 – 2018-02-08 15:39:24