bash 如何仅选择 AWK 脚本中的前 10 行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37097272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select only the first 10 rows in my AWK script
提问by lonewolf2288
I have a large CSV file. Basically what I want to do is display only the first 5 columns (which I can) but I also only want to display the first 10 rows, which is what I can't figure out. Right now this is the .awk file script I have:
我有一个很大的 CSV 文件。基本上我想做的是只显示前 5 列(我可以)但我也只想显示前 10 行,这是我无法弄清楚的。现在这是我拥有的 .awk 文件脚本:
"BEGIN {FS = ","}
{print ", " ", " ", " ", " }"
In Tera Term this is the command I use, which results in the first 5 columns of every row to be displayed: $awk -f example.awk example.csv
在 Tera Term 中,这是我使用的命令,它会显示每行的前 5 列:$awk -f example.awk example.csv
I have tried a couple of ways of using NR<=11 but that keeps coming up with error messages when trying to run on Tera Term.
我已经尝试了几种使用 NR<=11 的方法,但是在尝试在 Tera Term 上运行时不断出现错误消息。
Please help!
请帮忙!
回答by John1024
Try:
尝试:
awk -F, '{print ,,,,} NR==10{exit}' OFS=', ' file.csv
[Note that the awk code is in single-quotes, not double-quotes. That is necessary to prevent the shell from misinterpreting $1
, etc., as shell variables and expanding them.]
[注意 awk 代码是单引号,不是双引号。这对于防止 shell 将$1
等误解释为 shell 变量并对其进行扩展是必要的。]
How it works
这个怎么运作
-F,
tells awk to use,
as the field separator on input. This is equivalent to but much briefer thanBEGIN {FS = ","}
.print $1,$2,$3,$4,$5
tells awk to print the first five columns. (See below for why the", "
strings aren't needed in this version.)NR==10{exit}
tells awk to exit on the tenth line.OFS=', '
tells awk to use comma-space as the field separator on output. This setting makes much of the quoting in the original code unnecessary.
-F,
告诉 awk,
用作输入的字段分隔符。这相当于但比BEGIN {FS = ","}
.print $1,$2,$3,$4,$5
告诉 awk 打印前五列。(有关为什么", "
在此版本中不需要字符串的原因,请参见下文。)NR==10{exit}
告诉 awk 在第十行退出。OFS=', '
告诉 awk 使用逗号空格作为输出的字段分隔符。此设置使原始代码中的大部分引用变得不必要。
回答by Michael Vehrs
Alternatively,
或者,
awk -F, 'NR==1, NR==10 {print ,,,,}' OFS=', ' file.csv
This solution has the slight advantage that it also works for ranges that do not start with the first line, e.g. NR==21, NR==35
.
这个解决方案有一个小小的优势,它也适用于不以第一行开头的范围,例如NR==21, NR==35
.