replace - 如何在搜索字符串最后一次出现后的行上插入文本?

标签 replace insert find

我为了这个问题绞尽脑汁花了几个小时。

我试图编写一个脚本,该脚本将在一组源 *.cpp 文件中最后一次出现现有包含文件之后插入额外的包含文件和注释。源文件位于一组递归目录中,因此我想我的脚本必须从查找开始。

例如,之前:

#include <a>
#include <b>
#include <c>
// source code...

之后:

#include <a>
#include <b>
#include <c>
// This is the extra include file
#include <d>
// source code...

最佳答案

你可以在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”文件,然后查找最后一个包含所在的行并将该行添加到该行并重写该文件。奇迹般有效。如有任何改进意见,我们将不胜感激。

关于replace - 如何在搜索字符串最后一次出现后的行上插入文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16816778/

相关文章:

vba - 查找日期是否存在于单元格范围中(Excel VBA)

c# - 在 Ruby 中将每个匹配的字符串替换为不同的值

C++ - string.replace 不起作用

Mysql: SELECT * FROM ....没有一个字段

python - Pyodbc executemany 只返回插入的最后一个元素

linux - 使用 find 和 ffmpeg (Linux) 在命令行上批量转换多媒体文件

未打印python子字符串

c++ - 用长字符串中的另一个子字符串替换所有出现的子字符串

pandas - 更改列表中列中的值

php - 如何用PHP/MySQL插入大量数据?