如何在文件Notepad ++列表中用不同的字符串替换字符串

时间:2013-11-10 01:09:02

标签: string replace notepad++

您好我有一个文件100文件的列表。

每个文件都包含

a = a & "blahblhablhablha"
a = a & "blahblhablhablha"
a = a & "blahblhablhablha"
a = a & "blahblhablhablha"

我希望所有文件都应该像这样替换

public file1
a1 = a1 & "blahblhablhablha"
a1 = a1 & "blahblhablhablha"
a1 = a1 & "blahblhablhablha"
a1 = a1 & "blahblhablhablha"
a1x = a1
end file

在文件二中,它应该是

public file2
a2 = a2 & "blahblhablhablha"
a2 = a2 & "blahblhablhablha"
a2 = a2 & "blahblhablhablha"
a2x = a2
end file

和soo on ...直到最后100个文件

让我们说我们的上一个文件看起来像

public file100
a100 = a100 & "blahblhablhablha"
a100 = a100 & "blahblhablhablha"
a100 = a100 & "blahblhablhablha"
a100x = a100
end file

1 个答案:

答案 0 :(得分:1)

你只是不能在Notepad ++中执行此操作!

原因是您在使用正则表达式时无法访问您编辑的文件的名称,也无法访问已编辑文件的计数器(这就是您编辑文件的方式)。从理论上讲,可以通过手动处理每个文件并每次对文件名进行硬编码来实现,但正如jgritty建议的那样,最好的办法是使用更合适的工具,如sed,Python,Perl等。

所以这是解决问题的Python解决方案:

from os import listdir
from os.path import isfile,join

path="yourfolder" #change it to your path of files

for filename in listdir(path): #read all entries from path
    if isfile(join(path,filename)): #keep only the files
        with open(join(getcwd(),path,filename),"r+") as file: #open each file
            num=filename #I assume that the files are named 1,...,100. If that's not the case then change this to a counter
            content=file.readlines() #pull the file contents
            content.insert(0,"public file%s\n" % num) #insert the 1st line
            content.append("a%sx = a%s\nend file\n" % (num,num)) #append the last lines
            file.seek(0) #reset file's current position in order to overwrite it
            for line in content:
                line=line.replace("a = a","a%s = a%s" % (num,num)) #edit the lines
                file.write(line) #write the output