简体   繁体   English

使用通配符搜索和替换文本文件中的字符串

[英]Search and Replace Strings in a Text File Using Wildcards

Trying to do a search/replace in python using wildcards on the contents of a text file: 尝试在文本文件的内容上使用通配符在python中进行搜索/替换:

If the contents of the text file looks like: 如果文本文件的内容如下所示:

"all_bcar_v0038.ma";
"all_bcar_v0002.ma";
"all_bcar_v0011.ma";
"all_bcar_v0011.ma";

Looking to replace all the version numbers with v1000 to get this: 希望将所有版本号替换为v1000以获得此信息:

"all_bcar_v1000.ma";
"all_bcar_v1000.ma";
"all_bcar_v1000.ma";
"all_bcar_v1000.ma";

And have the file written out. 并把文件写出来。

I've tried the below but what happens is the script only catches the first version number, leaving the others untouched: 我在下面尝试过,但是发生的是该脚本仅捕获第一个版本号,而其他版本保持不变:

def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
    if searchExp in line:
    line = line.replace(searchExp,replaceExp)
    sys.stdout.write(line)

rigs = ['all_bcar']
rigs_latest = ['all_bcar_v1000']

old_pattern = []
old_compiled = []
old = []
old_version = []

for rig in range(len(rigs)):
    old_pattern.append("/" + rigs[rig] + "_(.*).ma")
    fin = open(txt_file, "r")

    old_compiled.append(re.compile(old_pattern[rig]))
    old.append(old_compiled[rig].search(fin.read()))
    old_version.append(old[rig].group(1).strip())
    old_rig = (rigs[rig] + "_" + old_version[rig])
    replaceAll(txt_file,old_rig,rigs_latest[rig])


fin.close()

Not sure how to keep the search looping to find other versions and to avoid the versions that have already been replaced, to skip any versions that equal "v1000". 不确定如何保持搜索循环以查找其他版本并避免已被替换的版本,以跳过等于“ v1000”的任何版本。

Your life would be vastly improved with the use of regexes . 使用正则表达式将极大地改善您的生活。 You should be able to do this in 2 lines (assuming I understand the problem correctly): 您应该能够分两行执行此操作(假设我正确理解了该问题):

import re

for line in fileinput.input(file, inplace=1):
  re.sub(r"_v\d{4}", "_v1000", line)

Try - 尝试-

import re

re.sub("_v\d{4}", "_v1000.", string)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM