[英]sed -unterminated `s' command
我使用以下sed命令來查找舊字符串並將其替換為新字符串:
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 / 6.9.28 /6.9.29/'目錄名/文件名
無需調用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))
編輯:
結合喬蘭的評論:
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))
我不知道這是否是唯一的錯誤,但是您可能希望在路徑名之前加一個空格,以將其與命令分開:
cmd = "sed -i 's/%s/%s/' %s"%(oldstr, newstr, "path_to/filename")
(我改用了字符串格式運算符,以使sed
命令行的整體結構更容易看清)。
我不知道您的命令出了什么問題。 無論如何,使用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])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.