您可以在 python 中执行此操作,我在下面制作了一个示例脚本:
import os
def find_last_include(file_name):
""" Returns last line with an include statement at the start """
last_include_line = 0
with open(file_name, "r") as f:
for i,line in enumerate(f):
if line.strip().startswith("#include"):
last_include_line = max(i, last_include_line)
return last_include_line
def insert_line(file_name, last_include_line_no, new_line):
""" New line should end with \n"""
try:
with open(file_name,"r+") as f:
print "Opening: {0}".format(file_name)
# File is all the lines in the file as a list
file = f.readlines()
# last include line is the line we are going to replace the last inculde
# with the last include + the new line we want
last_include_line = file[last_include_line_no] + new_line
file[last_include_line_no] = last_include_line
print "Inserting: '{0}' On line: {1}".format(new_line.strip(), last_include_line_no)
f.seek(0) # Seek back to the start of the file
for line in file:
f.write(line) # Write the lines with changes to the file
except IOError as e:
print e
return None
if __name__ == '__main__':
c_files = find_all(".c","Y:\\Python Stuff")
line = "#include <c>\n"
for c_file in c_files:
insert_line(c_file, find_last_include(c_file), line)
print "Finished Inserting lines"
这打印:
SEARCHING FOR FILES..
FOUND FILE: Y:\Python Stuff\prog.c
Finished finding
Opening: Y:\Python Stuff\prog.c
Inserting: #include <c> On line: 34
Finished Inserting lines
这样做是从给定文件夹开始查找所有“.c”文件,然后查找最后一个包含所在的行并将该行添加到该行并重写文件。奇迹般有效。不过,任何改进意见将不胜感激。