Perl 正则表达式从命令行对文件进行操作 [英] Perl regex to act on a file from the command line
问题描述
在一个文件中,说 xyz.txt 我想替换任何数字的模式,后跟一个点示例:1.,2.,10.,11.等等.有一个空格.怎么在命令行写一个perl命令作用于文件做上面的事情,应该用什么正则表达式?
In a file, say xyz.txt i want to replace the pattern of any number followed by a dot example:1.,2.,10.,11. etc.. with a whitespace. How to compose a perl command on the command line to act on the file to do the above, what should be the regex to be used ?
请帮忙谢谢.
推荐答案
这必须是 Perl oneliner 吗?
This HAS to be a Perl oneliner?
perl -i -pe 's/\d+\./ /g' <fileName>
Perl 命令行选项:-i
用于指定对输入文件执行的操作.如果你不给它一个文件扩展名,原始文件就会丢失并被 Perl 修改过的输出替换.例如,如果我有这个:
The Perl command line options: -i
is used to specify what happens to the input file. If you don't give it a file extension, the original file is lost and is replaced by the Perl munged output. For example, if I had this:
perl -i.bak -pe 's/\d+\./ /g' <fileName>
原始文件将以 .bak
后缀存储,
The original file would be stored with a .bak
suffix and <fileName> itself would contain your output.
-p
意味着将您的 Perl 程序封装在一个打印循环中,看起来有点如下:
The -p
means to enclose your Perl program in a print loop that looks SOMEWHAT like this:
while ($_ = <>) {
<Your Perl one liner>
print "$_";
}
这是对正在发生的事情的稍微简化的解释.您可以通过从命令行执行 perldoc perlrun
来查看实际的 perl 循环.主要思想是它允许您像 sed
或 awk
一样对文件的每一行进行操作.
This is a somewhat simplified explanation what's going on. You can see the actual perl loop by doing a perldoc perlrun
from the command line. The main idea is that it allows you to act on each line of a file just like sed
or awk
.
-e
只包含您的 Perl 命令.
The -e
simply contains your Perl command.
您也可以进行文件重定向:
You can also do file redirection too:
perl -pe 's/\d+\./ /g' < xyz.txt > xyz.txt.out
这篇关于Perl 正则表达式从命令行对文件进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!