Bash 确定awk脚本开始部分中的NR
在awk处理输入文件之前,我需要知道需要多少记录 为了确定这一点,我在awk脚本的BEGIN段中有以下代码Bash 确定awk脚本开始部分中的NR,bash,awk,Bash,Awk,在awk处理输入文件之前,我需要知道需要多少记录 为了确定这一点,我在awk脚本的BEGIN段中有以下代码 BEGIN { p = "" j = 1 getline # Activates the FILENAmE variable which normally is not available in the BEGIN section of an awk script. n = system("wc -l " FILENAME)
BEGIN {
p = ""
j = 1
getline # Activates the FILENAmE variable which normally is not available in the BEGIN section of an awk script.
n = system("wc -l " FILENAME) # Assign the result (i.e. number of records in FILENAME) to the n variable.
gsub(FILENAME, "|", n) # Remove the input file name appended to the result and replace with "|" just to see what it's done!
print n # See what the hell has happened.
}
我希望看到n显示记录的数量,但是我的输出看起来像这样
12 accounts12
0
“accounts12”是我的输入文件的名称….
系统
返回其退出状态(如果成功完成,通常为0)。所以这句话:
n = system("wc -l " FILENAME)
只会导致wc
命令的输出像往常一样打印在屏幕上,然后n
被设置为退出代码0
这说明:
12 accounts12
0
第一行是wc
的输出,第二行是n
的值
您可以尝试:
BEGIN {
"wc -l " ARGV[1] | getline n;
sub(ARGV[1], "|", n);
print n;
}
这将获得您的n
。它的好处是不会占用文件的第一行。您也可以这样做
$ awk 'NR==FNR{n=NR; next} FNR==1{print n} ...' file{,}
第一轮计算记录数,第二轮打印计数并完成其余处理 awk的另一种方式:
- 将FS设置为\n(每行都是一个字段)
- 将RS设置为\0(仅一条记录)
- 田间作业
awk-F'\n'-vRS='\0'
{
打印NF
对于(i=1;ij=拆分($i,a,“”)
打印“字段编号=“j
}
}“填充
wc
,并在脚本内部使用其输出:
awk -v nr="$(wc -l < file)" '{print nr, NR, $0}' file
awk-v nr=“$(wc-l
e、 g:
$seq 3>文件
$awk-v nr=“$(wc-l<文件)”{print nr,nr,$0}文件
3 1 1
3 2 2
3 3 3
连接到“getline n”的管道不工作。我收到以下错误…“sh:1:0:not found”抱歉,输入错误。我漏掉了一个空格,你的输入总是一个文件还是一个来自管道的流?
$ seq 3 > file
$ awk -v nr="$(wc -l < file)" '{print nr, NR, $0}' file
3 1 1
3 2 2
3 3 3