Perl:从文本文件的第 4 列减去一个常量 (8)
Perl: Minus a constant (8) from 4th column of a text file
我的代码有效,只是它在输出文件的开头打印了一些垃圾。我可以手动删除它,但更希望我的脚本能够工作。输入文件是 19 列由“,”(逗号 space)分隔的数字数据,每列的标题都在第 0 行(我想跳过,另一个问题)。
我用 ./column3Minus8.pl INPUTFILE > OUTPUT.txt
调用我的文件
#!/usr/bin/perl
use strict;
while(<>) {
my @columns = split ", ", $_;
$columns[3] = sprintf("%.5f", $columns[3] - 8);
print join ", ", @columns;
}
output.txt开头的垃圾是
#!/usr/bin/perl
, , , -8.00000
, , , -8.00000use strict;
, , , -8.00000
, , , -8.00000while(<>) {
, , , -8.00000 my @columns = split ", ", $_;
, -8.00000 $columns[3] = sprintf("%.5f", $columns[3] - 8);
, , -8.00000 print join ", ", @columns;
, -8.00000}, , , -8.00000
EDITFIX:我在命令行调用中调用了 perl 文件两次,这导致了垃圾。 “./column3Minus8.pl column3Minus8.pl INPUTFILE > OUTPUT.txt”糟糕。不过,我仍然想知道如何跳过第一行。并替换常量。
TODO:将常量 8 替换为 var。跳过第 0 行,这样它就不会被编辑。
您的程序还有一些小问题。您还应该有 use warnings
,并且您应该 chomp
每一行,以防它是您要修改的 last 列。
此程序添加了必要的代码,以从命令行中获取要从第四列中减去的值,并复制文件的第一行。
你应该运行这样
column3minus.pl 8 inputfile > outputfile
#!/usr/bin/perl
use strict;
use warnings;
my $delta = shift;
print scalar <>; # Duplicate first line
while (<>) {
chomp;
my @columns = split /,\s*/;
$columns[3] = sprintf '%.5f', $columns[3] - $delta;
print join(', ', @columns), "\n";
}
我的代码有效,只是它在输出文件的开头打印了一些垃圾。我可以手动删除它,但更希望我的脚本能够工作。输入文件是 19 列由“,”(逗号 space)分隔的数字数据,每列的标题都在第 0 行(我想跳过,另一个问题)。
我用 ./column3Minus8.pl INPUTFILE > OUTPUT.txt
调用我的文件 #!/usr/bin/perl
use strict;
while(<>) {
my @columns = split ", ", $_;
$columns[3] = sprintf("%.5f", $columns[3] - 8);
print join ", ", @columns;
}
output.txt开头的垃圾是
#!/usr/bin/perl
, , , -8.00000
, , , -8.00000use strict;
, , , -8.00000
, , , -8.00000while(<>) {
, , , -8.00000 my @columns = split ", ", $_;
, -8.00000 $columns[3] = sprintf("%.5f", $columns[3] - 8);
, , -8.00000 print join ", ", @columns;
, -8.00000}, , , -8.00000
EDITFIX:我在命令行调用中调用了 perl 文件两次,这导致了垃圾。 “./column3Minus8.pl column3Minus8.pl INPUTFILE > OUTPUT.txt”糟糕。不过,我仍然想知道如何跳过第一行。并替换常量。
TODO:将常量 8 替换为 var。跳过第 0 行,这样它就不会被编辑。
您的程序还有一些小问题。您还应该有 use warnings
,并且您应该 chomp
每一行,以防它是您要修改的 last 列。
此程序添加了必要的代码,以从命令行中获取要从第四列中减去的值,并复制文件的第一行。
你应该运行这样
column3minus.pl 8 inputfile > outputfile
#!/usr/bin/perl
use strict;
use warnings;
my $delta = shift;
print scalar <>; # Duplicate first line
while (<>) {
chomp;
my @columns = split /,\s*/;
$columns[3] = sprintf '%.5f', $columns[3] - $delta;
print join(', ', @columns), "\n";
}