我一直使用Perl命令行一个-ne选项多年,主要是以sed的方式处理文本文件。例:
- cat in.txt | perl -ne "s/abc/def/; s/fgh/hij/; print;" > out.txt
我不知道我在哪里学到了,只有今天才读到perlrun,发现有其他形式(例如perl -pe)。
我还应该知道perl -ne?
解决方法
perl -ne’CODE’等同于程序
- while (<>) {
- CODE
- }
perl -ane’CODE’和perl -F / PATTERN / -ane也是很好的习语。他们相当于
- while (<>) {
- @F = split /\s+/,$_;
- CODE
- }
和
- while (<>) {
- @F = split /PATTERN/,$_;
- CODE
- }
示例:高级grep:
- perl -ne 'print if/REGEX1/&&!/REGEX2/&&(/REGEX3/||/REGEX4/&&!/REGEX5/)' input
- perl -F/,/ -ane 'print if $F[2]==4&&$F[3]ge"2009-07-01"&&$F[3]lt"2009-08-01"' file.csv
使用不匹配的大括号的一个特别聪明的例子是here。