[英]Bash Awk to print number of letters in each word
Hey all so I am writing a bash script that will take a file with a single line such as: 嘿所有,所以我正在编写一个bash脚本,它将采用一行文件,例如:
Hello this is my test sentence.
And count how many letter there are in each word and produce output such as: 并计算每个单词中有多少个字母并生成输出,例如:
5 4 2 2 4 4
This is what I have written: 这就是我写的:
#!/bin/bash
awk 'BEGIN {k=1}
{
for(i=1; i<=NF; i++){
stuff[k]=length($i)
printf("%d ", stuff[k])
k++
}
}
END {
printf("%d ", stuff[k])
printf("\n")
}'
and it gives me the output: 它给了我输出:
5 4 2 2 4 4
It is not recognizing how many letters there are in the last word of the sentence. 它无法识别句子的最后一个单词中有多少个字母。 Instead it is using the second to last number again.
相反,它再次使用倒数第二个数字。 Where I am going wrong?
我哪里错了?
No need for awk: 不需要awk:
echo Hello this is my test sentence. | {
read -a words
for ((i=0 ; i<${#words[@]}; i++)) ; do
words[i]=${#words[i]}
done
echo "${words[@]}"
}
Using bash only : 仅使用bash:
[ ~]$ str="Hello this is my test sentence"
[ ~]$ for word in $str; do echo -n "${#word} "; done; echo ""
5 4 2 2 4 8
Another solution with bash array : bash数组的另一个解决方案:
[ ~]$ echo $str|(read -a words; for word in "${words[@]}"; do echo -n "${#word} "; done; echo "")
5 4 2 2 4 8
Assuming that by "word" you mean text separated by spaces, this will literally count how many letter there are in each word
as requested: 假设通过“单词”表示由空格分隔的文本,这将按字面
count how many letter there are in each word
所要求的count how many letter there are in each word
:
$ cat file
Hello this is my test sentence.
and here is another sentence
$ awk '{for (i=1;i<=NF;i++) $i=gsub(/[[:alpha:]]/,"",$i)}1' file
5 4 2 2 4 8
3 4 2 7 8
and if you wanted to count all characters, not just letters, it'd be: 如果你想计算所有字符,而不仅仅是字母,那就是:
$ awk '{for (i=1;i<=NF;i++) $i=length($i)}1' file
5 4 2 2 4 9
3 4 2 7 8
$ echo Hello this is my test sentence. | awk '{for (i=1;i<=NF;i++) {printf " " length($i)}; print "" }'
5 4 2 2 4 9
Or, with the sentence in a file called sentence
: 或者,将句子放在一个名为
sentence
的文件中:
$ awk '{for (i=1;i<=NF;i++) {printf " " length($i)}; print "" }' sentence
5 4 2 2 4 9
If we want to remove the leading space: 如果我们想要删除前导空格:
$ awk '{for (i=1;i<=NF;i++) {printf "%s%s",length($i),(i==NF?"\n":FS)} }' sentence
5 4 2 2 4 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.