Perl 有一些简单的单行技巧,可以帮助很方便的实现一些文件编辑查找。介绍几个常用的方法:
C:\>perl -h Usage: D:\Perl\bin\perl.exe [switches] [--] [programfile] [arguments] -0[octal] specify record separator (\0, if no argument) -a autosplit mode with -n or -p (splits $_ into @F) -C[number/list] enables the listed Unicode features -c check syntax only (runs BEGIN and CHECK blocks) -d[:debugger] run program under debugger -D[number/list] set debugging flags (argument is a bit mask or alphabets) -e program one line of program (several -e's allowed, omit programfile) -E program like -e, but enables all optional features -f don't do $sitelib/sitecustomize.pl at startup -F/pattern/ split() pattern for -a switch (//'s are optional) -i[extension] edit <> files in place (makes backup if extension supplied) -Idirectory specify @INC/#include directory (several -I's allowed) -l[octal] enable line ending processing, specifies line terminator -[mM][-]module execute "use/no module..." before executing program -n assume "while (<>) { ... }" loop around program -p assume loop like -n but print line also, like sed -P run program through C preprocessor before compilation -s enable rudimentary parsing for switches after programfile -S look for programfile using PATH environment variable -t enable tainting warnings -T enable tainting checks -u dump core after parsing program -U allow unsafe operations -v print version, subversion (includes VERY IMPORTANT perl info) -V[:variable] print configuration summary (or a single Config.pm variable) -w enable many useful warnings (RECOMMENDED) -W enable all warnings -x[directory] strip off text before #!perl line and perhaps cd to directory -X disable all warningsperl -ne 'scirpt' filename
循环读入文件并根据脚本处理每一行
perl -pe 'scirpt' filename
循环读入文件并根据脚本处理每一行,不同的是打印处理后每一行的内容
perl -i.bak -pe 's/string1/string2/g' filename
替换文件中每一行的字符串string1,并将原始文件备份为.bak。注意,替换的时候需要使用参数p
perl -ne 'print if 1..10' filename
对文件的前10行处理,行数从1开始计算
perl -ne 'print if /START/../END/' filename
对文件内容,从包含START 行开始打印,到包含END行结束。如果包含多个这样的段落,都打印出来,如果没有行包含END,则打印到文件结束
最后看一下实际执行中的代码
D:\Tmp>perl -MO=Deparse -ne "print if 1..10" test.pl LINE: while (defined($_ = <ARGV>)) { print $_ if 1 .. 10; } -e syntax OK D:\Tmp>perl -MO=Deparse -pe "print if 1..10" test.pl LINE: while (defined($_ = <ARGV>)) { print $_ if 1 .. 10; } continue { print $_; } -e syntax OK