Perl是著名的脚本语言,擅长文本处理。我们这里要学习的,是perl的命令行用法。perl的命令行用法的作用与sed命令类似,但由于可以使用perl正则表达式,所以熟悉perl的人有时更喜欢用perl的命令行用法来代替sed处理文本。
文本处理,类似于sed
perl -pe [file]
perl -ne [file]
-e 在命令行而不是在脚本中执行perl -n 使 Perl 隐式地循环遍历指定的文件,并只打印代码里规定输出的行。自动循环, 相当于 while(<>) { 脚本; } -p 使 Perl 隐式地循环遍历指定的文件,同时打印所有的行。自动循环+自动输出, 相当于 while(<>) { 脚本; print; }
我们可以用perl的命令行用法来完成文本替换(也可以用sed):
[peter@ibi98 perl]$ cat demo_perl Social behaviour emerges from the local environment but is constrained by the animal's life history and its evolutionary lineage. In this perspective, we consider the genus Drosophila and provide an overview of how these constraints can shape how individuals interact. [peter@ibi98 perl]$ perl -pe 's/behaviour/BEHAVIOUR/g' demo_perl Social BEHAVIOUR emerges from the local environment but is constrained by the animal's life history and its evolutionary lineage. In this perspective, we consider the genus Drosophila and provide an overview of how these constraints can shape how individuals interact.
以命令行方式运行perl必须有-e选项。-p选项输出所有的行,无论该行有没有被处理过。
代码部分与perl脚本运行方式完全一样:
[peter@ibi98 perl]$ cat demo_perl |perl -ne 'if($_ =~ m/ the /){print "YES: $_";}'
YES: Social behaviour emerges from the local environment
YES: but is constrained by the animal's life history and its
这里用了-n而不是-p选项,只输出符合条件的行(如果行中有 the 就输出该行,并在行首添加YES:)。
如果您熟悉Perl语言,就可以在Shell下以命令行的方式方便的使用Perl的语法来处理文本。