如何在AWK中以CSV格式打印一系列列? [英] How to print a range of columns in a CSV in AWK?
问题描述
使用awk
,我可以在CSV中打印任何列,例如,这将在file.csv
中打印第10列.
With awk
, I can print any column within a CSV, e.g., this will print the 10th column in file.csv
.
awk -F, '{ print $10 }' file.csv
如果我需要打印5-10列(包括逗号),我只会这样知道:
If I need to print columns 5-10, including the comma, I only know this way:
awk -F, '{ print $5","$6","$7","$8","$9","$10 }' file.csv
如果我要打印许多列,则此方法不太好.在awk
中以CSV格式打印一定范围的列是否有更简单的语法?
This method is not so good if I want to print many columns. Is there a simpler syntax for printing a range of columns in a CSV in awk
?
推荐答案
在awk中执行此操作的标准方法是使用for循环:
The standard way to do this in awk is using a for loop:
awk -v s=5 -v e=10 'BEGIN{FS=OFS=","}{for (i=s; i<=e; ++i) printf "%s%s", $i, (i<e?OFS:ORS)}' file
但是,如果定界符很简单(如您的示例中所示),则您可能更喜欢使用cut
:
However, if your delimiter is simple (as in your example), you may prefer to use cut
:
cut -d, -f5-10 file
值得一提的是Perl(使用-a
启用自动拆分模式):
Perl deserves a mention (using -a
to enable autosplit mode):
perl -F, -lane '$"=","; print "@F[4..9]"' file
这篇关于如何在AWK中以CSV格式打印一系列列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!