0

次の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

4

3 に答える 3

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))
于 2012-06-19T18:00:45.167 に答える
1

これだけが間違っているかどうかはわかりませんが、パス名の前にスペースを入れて、コマンドと区切る必要があるでしょう。

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

sed(コマンド ラインの全体的な構造を見やすくするために、文字列書式演算子に切り替えました)。

于 2012-06-19T17:57:50.620 に答える
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])
于 2012-06-19T17:51:08.663 に答える