【发布时间】:2011-01-29 13:31:24
【问题描述】:
我有一个包含以下内容的文件 1000 行,格式如下:
abc def ghi gkl
如何编写 Perl 脚本以仅打印第一个和第三个字段?
abc ghi
【问题讨论】:
我有一个包含以下内容的文件 1000 行,格式如下:
abc def ghi gkl
如何编写 Perl 脚本以仅打印第一个和第三个字段?
abc ghi
【问题讨论】:
perl -lane 'print "@F[0,2]"' file
【讨论】:
-lae 不适用于 Perl v5.18.4。需要-n。
如果还没有适合你的答案,我会尝试获得赏金;-)
#!/usr/bin/perl
# Lines beginning with a hash (#) denote optional comments,
# except the first line, which is required,
# see http://en.wikipedia.org/wiki/Shebang_(Unix)
use strict; # http://perldoc.perl.org/strict.html
use warnings; # http://perldoc.perl.org/warnings.html
# http://perldoc.perl.org/perlsyn.html#Compound-Statements
# http://perldoc.perl.org/functions/defined.html
# http://perldoc.perl.org/functions/my.html
# http://perldoc.perl.org/perldata.html
# http://perldoc.perl.org/perlop.html#I%2fO-Operators
while (defined(my $line = <>)) {
# http://perldoc.perl.org/functions/split.html
my @chunks = split ' ', $line;
# http://perldoc.perl.org/functions/print.html
# http://perldoc.perl.org/perlop.html#Quote-Like-Operators
print "$chunks[0] $chunks[2]\n";
}
要运行这个脚本,假设它的名字是script.pl,调用它
perl script.pl FILE
其中FILE 是您要解析的文件。另见http://perldoc.perl.org/perlrun.html。祝你好运! ;-)
【讨论】:
split /\s+/ 替换split ' ' 以分割各种空格(是否重复)甚至可能会很有趣
' ' 在 Perl 中有特殊的含义。
awk 仿真:“当PATTERN 被省略或由字符串组成时,split 模拟命令行工具awk 的默认行为单个空格字符(例如 ' ' 或 "\x20" ,但不是例如 / / )。在这种情况下,EXPR 中的任何前导空格在拆分发生之前都会被删除,而 PATTERN 则被视为@ 987654334@"
对于像 perl 这样强大的东西来说,这真的是一种浪费,因为你可以在一行微不足道的 awk 中做同样的事情。
awk '{ print $1 $3 }'
【讨论】:
while ( <> ) {
my @fields = split;
print "@fields[0,2]\n";
}
而且只是为了多样化,在 Windows 上:
C:\Temp> perl -pale "$_=qq{@F[0,2]}"
在 Unix 上
$ perl -pale '$_="@F[0,2]"'
【讨论】:
按照 perl 单线:
perl -ane 'print "@F[0,2]\n"' file
或作为可执行脚本:
#!/usr/bin/perl
use strict;
use warnings;
open my $fh, '<', 'file' or die "Can't open file: $!\n";
while (<$fh>) {
my @fields = split;
print "@fields[0,2]\n";
}
像这样执行脚本:
perl script.pl
或
chmod 755 script.pl
./script.pl
【讨论】:
我确定我不应该得到赏金,因为问题要求在 perl 中给出结果,但无论如何:
在 bash/ksh/ash/etc 中:
cut -d " " -f 1,3 "file"
在 Windows/DOS 中:
for /f "tokens=1-4 delims= " %i in (file) do (echo %i %k)
优点:和其他人说的一样,不用学Pearl、Awk,什么都不懂,只知道一些工具。使用“>”和“>>”运算符可以将两个调用的结果保存到磁盘。
【讨论】:
while(<>){
chomp;
@s = split ;
print "$s[0] $s[2]\n";
}
请也开始浏览documentation
【讨论】:
/\s+/ 上的拆分类似于split(' '),只是任何前导空格都会产生一个空的第一个字段。没有参数的拆分确实在内部执行split(' ', $_)。
#!/usr/bin/env perl
open my$F, "<", "file" or die;
print join(" ",(split)[0,2])."\n" while(<$F>);
close $F
【讨论】:
一个简单的方法是:
(split)[0,2]
例子:
$_ = 'abc def ghi gkl';
print( (split)[0,2] , "\n");
print( join(" ", (split)[0,2] ),"\n");
命令行:
perl -e '$_="abc def ghi gkl";print(join(" ",(split)[0,2]),"\n")'
【讨论】: