2012-06-19 121 views
0

我用下面的sed命令來查找和替換舊的字符串,一個新問題:sed的-unterminated'S'命令

cmd = "sed -i 's/"+oldstr+"/"+newstr+"/'"+ "path_to/filename" #change the string in the file 
    os.system(cmd) # am calling the sed command in my python script 

,但我得到這個錯誤:

sed: -e expression #1, char 8: unterminated `s' command 

人告訴我我的sed命令有什麼問題? 或者我給出文件名的方式有問題嗎?

更新: 反響,命令: SED -i 'S/28年6月9日 /6.9.29/' 目錄名/文件名

+2

呼應的是'cmd',告訴我們什麼是在那裏... – Wrikken

+1

看起來像'oldstr'或'newstr'中的東西。正如@Wrikken所指出的那樣,由於你在「s」之前似乎有一個嘀嗒聲,所以你的迴應是錯誤的--- ---你是否必須使用'sed'來執行此操作? – swasheck

+4

在python腳本中使用'sed'看起來非常愚蠢和骯髒的破解,並且會破壞可移植性。如果它打算只在Linux中運行,那麼沒關係。而'os.system'也不推薦使用'subprocess'模塊。 – KurzedMetal

回答

3

如果不調用sed

with open("path_to/filename") as f: 
    file_lines = f.readlines() 
    new_file = [line.replace(oldstr,newstr) for line in file_lines] 

open("path_to/filename","w").write(''.join(new_file)) 

編輯:

結合Joran的評論:

with open("path_to/filename") as f: 
    file = f.read() 
    newfile = file.replace(oldstr,newstr) 

open("path_to/filename","w").write(newfile) 

甚至

with open("path_to/filename") as f: 
    open("path_to/filename","w").write(f.read().replace(oldstr,newstr)) 
+1

你不能只讀()而不是readlines,只做一個替換(因爲它應該取代所有發生?) –

+0

@JoranBeasley好點。更新 – swasheck

+0

這工作(儘管最後一塊代碼不工作)!謝謝.. – user1164061

0

我不知道什麼是你的命令去錯了。無論如何,你肯定會使用subprocess.call()功能更好。假設我們有一個文件:

$ cat test.txt 
abc 
def 

現在,如果我執行下面的程序:

import subprocess 
oldstr = 'a' 
newstr = 'AAA' 
path = 'test.txt' 
subprocess.call(['sed', '-i', 's/'+oldstr+'/'+newstr+'/', path]) 

我們得到這樣的:

$ cat test.txt 
AAAbc 
def 

另外,如果您oldstr/newstr有一些斜線(/)裏面,你的命令也會打破。我們可以通過一個轉義斜槓替換斜線解決它:

>>> print 'my/string'.replace('/', '\\/') 
my\/string 

所以,如果你有這樣的文件:

$ cat test.txt 
this is a line and/or a test 
this is also a line and/or a test 

,並要替換and/or,只是相應的更換斜線的變量:

import subprocess 
oldstr = 'and/or' 
newstr = 'AND' 
path = 'test.txt' 
subprocess.call(['sed', '-i', 's/'+oldstr.replace('/', '\\/')+'/'+newstr.replace('/', '\\/')+'/', path]) 

當然,它可以是多一點可讀:

import subprocess 
oldstr = 'and/or' 
newstr = 'AND' 
path = 'test.txt' 
sedcmd = 's/%s/%s/' % (oldstr.replace('/', '\\/'), newstr.replace('/', '\\/')) 
subprocess.call(['sed', '-i', sedcmd, path]) 
+0

used this:'import subprocess oldstr ='and/or' newstr ='AND' path ='test.txt' sedcmd ='s /%s /%s /'%(oldstr.replace('/ '','\\ /'),newstr.replace('/','\\ /')) subprocess.call(['sed','-i',sedcmd,path])'它仍然顯示同樣的錯誤 – user1164061

1

我不知道這是不是唯一的東西不對,但你可能想要的路徑名之前,將其從命令分離空間:

cmd = "sed -i 's/%s/%s/' %s"%(oldstr, newstr, "path_to/filename") 

(我切換到字符串格式化操作使sed命令行的整體結構更易於查看)。

+0

這也給出了同樣的錯誤 – user1164061