sed -unterminated的's'命令

时间:2012-06-19 17:41:41

标签: python sed

我使用以下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/'dirname / filename

3 个答案:

答案 0 :(得分: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 :(得分:1)

我不知道这是否是唯一的错误,但你可能想要在路径名前面留一个空格,将它与命令分开:

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

(我切换到字符串格式化运算符,以便更容易看到sed命令行的整体结构。)

答案 2 :(得分: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])
相关问题