2014-02-09 46 views
2

我正在处理一个需要用另一个文件替换第一行文件的python脚本。在python脚本中使用sed命令替换文件的第一行

#!/bin/bash#!/usr/bin/custom_shell

只有第一线必须改变,我试着在subprocess.call使用sed命令,但没有全成,可能有人请提出一个可爱又简单的方法来做到这一点。

+4

这个问题似乎是题外话,因为它是关于一个可爱而简单的方式来做一些事情,而不用提供任何信息来诊断问题。 – devnull

回答

0

根本不需要使用sedsubprocess

import os 
replacement, shebang_line = "#!/usr/bin/custom_shell\n", "" 

with open("InputFile.txt") as input_file, open("tempFile.txt") as output_file: 

    # Find the first non-empty line (which is assumed to be the shebang line) 
    while not shebang_line: 
     shebang_line = next(input_file).strip() 

    # Write the replacement line 
    output_file.write(replacement) 

    # Write rest of the lines from input file to output file 
    map(output_file.write, input_file) 

# rename the temporary file to the original input file 
os.rename("tempFile.txt", "InputFile.txt") 
+0

这实际上应该使用临时文件名(即'tempfile'模块)。 – Carpetsmoker

0

为什么不使用python打开文件,进行更改并将其写回文件?除非你的文件太大而无法保存在内存中。

for i in files_to_change: 
    with open(i,'rw') as f: 
     lines = f.readlines() 
     lines[lines.index("#!/bin/bash\n")] = "#!/usr/bin/custom_shell" 
     f.seek(0) 
     f.writelines(lines) 
1

要使用sed

sed -e '1s:#!/bin/bash:#!/usr/bin/custom_shell:' yourfile.py 

这将放置写到标准输出。要保存在与被替换的文本文件,而不是,使用-i标志:

sed -i '' -e '1s:#!/bin/bash:#!/usr/bin/custom_shell:' yourfile.py 
0

的最好办法是在地方修改文件

import fileinput 

for line in fileinput.FileInput("your_file_name", inplace=True): 
    print("#!/usr/bin/custom_shell") 
    break