简体   繁体   English

将包含搜索模式的行完全替换为另一行

[英]replace line that contains search pattern entirely with another line

I would like to replace every line that starts with a certain expression (example: <Output> ) with what I want the output path to be. 我想将以某种表达式(例如: <Output> )开头的每一行替换为我想要的输出路径。 I have found and got to work a python script that replaces one string with another, in every occurrence in a file - something like: 我发现并开始工作一个Python脚本,该脚本在文件中每次出现的情况下都将一个字符串替换为另一个字符串-类似于:

text = open( path ).read()
if output_pattern in text:
   open( path, 'w' ).write( text.replace( pattern, replace ) )

However I would like to replace the text.replace( pattern, replace ) with something that replaces the entire line that contains pattern with replace . 不过,我想,以取代text.replace( pattern, replace )的东西,代替了包含整个线patternreplace I have tried some things and failed miserably. 我尝试了一些事情,但失败了。

Note: I can read but not quite write python... 注意:我可以阅读但不能完全编写python ...

One of my failures did replace the pattern with the line. 我的失败之一确实用线代替了模式。 Actually, it replaced the entire file with only the replace pattern, as many times as it was needed... Yeah, not funny since I was doing a recursive search (and the previous attempt, to replace one string with another, worked perfectly, so I was brave and set my target directory as the root of what I want to work with) 实际上,它只用替换模式替换了整个文件,次数是需要的……是的,这很有趣,因为我正在进行递归搜索(上一次尝试用一个字符串替换另一个字符串的效果很好,所以我很勇敢,将目标目录设置为我要使用的目录的根目录)

There are other great examples that read line by line and write to an output file, and then copy the output file to the input file, but I got an error doing that. 还有其他一些很棒的示例,它们逐行读取并写入输出文件,然后将输出文件复制到输入文件,但是这样做却出错了。

I don't really want to use regex because the patterns that I might want to search for (and especially what I want to replace) (may) contain many special characters including backslashes, but these could be escaped if needed. 我真的不想使用正则表达式,因为我可能要搜索的模式(尤其是我要替换的模式)(可能)包含许多特殊字符,包括反斜杠,但是如果需要可以将其转义。

To replace lines with replace if they start with pattern : 如果行以pattern开头,则用replace替换行:

text = open(path).read()
new_text = '\n'.join(replace if line.startswith(pattern) else line
                                for line in text.splitlines())
open(path, 'w').write(new_text)

Or optimized for memory usage, and using the with statement, which is a bit more idiomatic: 或针对内存使用进行了优化,并使用with语句,这有点惯用语:

with open(input_path) as text, open(output_path, 'w') as new_text:
    new_text.write(''.join(replace if line.startswith(pattern) else line
                                for line in text))

You'll want to make sure replace has a newline character ( \\n ) in it for the latter example to work as you'd expect. 您将要确保replace中包含换行符( \\n ),以便后一个示例按预期工作。

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

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