使用 Perl 搜索和替换文件中的特定字符串 [英] Search and replace a particular string in a file using Perl
本文介绍了使用 Perl 搜索和替换文件中的特定字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
如何替换现有文件中的字符串Perl?
我需要创建一个在文件中进行搜索和替换的子程序.
I need to create a subroutine that does a search and replace in file.
这里是 myfiletemplate.txt 的内容:
Here's the contents of myfiletemplate.txt:
CATEGORY1=youknow_<PREF>
CATEGORY2=your/<PREF>/goes/here/
这是我的替换字符串:ABCD
Here's my replacement string: ABCD
我需要将
的所有实例替换为 ABCD
I need to replace all instances of <PREF>
to ABCD
推荐答案
又快又脏:
#!/usr/bin/perl -w
use strict;
open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);
foreach(@lines) {
$_ =~ s/<PREF>/ABCD/g;
}
open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);
也许最好不要将结果写回原始文件;而是将其写入副本并先检查结果.
Perhaps it i a good idea not to write the result back to your original file; instead write it to a copy and check the result first.
这篇关于使用 Perl 搜索和替换文件中的特定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文