问题描述
我复制了一些使用printf的代码来输出字符串在文件中出现的频率.
I copied some code that was using printf to output how often strings appeared in files.
awk ' BEGIN { print "The number of times a appears in the file:" ; }
/a/ { a_counter+=1 ; }
END { printf "%s\n", a_counter ; }
' $file
将模式修改为变量后,我想将模式包括在计数旁边的printf命令中:
After modifying the pattern to a variable, I wanted to include the pattern into the printf command, next to the count:
awk -v a="$GENE1" ' BEGIN { print "The number of times", a, " appears in the file are:" ; }
$0 ~ a { a_counter+=1 ; }
END { printf "%s\n", a, a_counter ; }
' $file
现在,它仅显示a的值,而不显示a_counter的值.我读到printf
更为复杂,可能不应该像使用print
那样添加多个用,"分隔的字符串.但是我找不到正确的方法吗?我当然可以坚持使用print
,但是我想了解在printf
的情况下我做错了什么?
Now it only prints the value of a, but not of a_counter. I read that printf
is more complex and I'm probably not supposed to add multiple strings separated with "," as I could do with print
. But I couldn't find the right way to do it? Of course I could stick with print
, but I would like to understand what I did wrong in case of printf
?
推荐答案
每个变量都需要一个格式字符串,例如%s
.因此,请尝试:
You need one format string, like %s
, for every variable. So, try:
printf "%s %s\n", a, a_counter
或者:
printf "pattern=%s and count=%s\n", a, a_counter
%s
将任何变量转换为字符串.如果变量是数字,则其他格式(如%f
或%e
)可让您更好地控制将数字转换为字符串的方式.有关详细信息,请参见man awk
.
%s
converts any variable to a string. If the variable is a number, other formats, like %f
or %e
, give you more control over how the number is converted to a string. See man awk
for details.
$ awk -v a="genie" -v a_counter=3 'BEGIN{ printf "%s %s\n", a, a_counter }'
genie 3
$ awk -v a="genie" -v a_counter=3 'BEGIN{ printf "pattern=%s and count=%s\n", a, a_counter }'
pattern=genie and count=3
$ awk -v a="genie" -v a_counter=3 'BEGIN{ printf "pattern=%s and count=%7.2f\n", a, a_counter }'
pattern=genie and count= 3.00
$ awk -v a="genie" -v a_counter=3 'BEGIN{ printf "pattern=%s and count=%9.2e\n", a, a_counter }'
pattern=genie and count= 3.00e+00
这篇关于awk的printf插入多个变量的正确语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!