繁体   English   中英

Bash Awk打印每个单词中的字母数

[英]Bash Awk to print number of letters in each word

嘿所有,所以我正在编写一个bash脚本,它将采用一行文件,例如:

Hello this is my test sentence.

并计算每个单词中有多少个字母并生成输出,例如:

5 4 2 2 4 4

这就是我写的:

#!/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")
}'

它给了我输出:

5 4 2 2 4 4

它无法识别句子的最后一个单词中有多少个字母。 相反,它再次使用倒数第二个数字。 我哪里错了?

不需要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[@]}"
}

仅使用bash:

[ ~]$ str="Hello this is my test sentence"
[ ~]$ for word in $str; do echo -n "${#word} "; done; echo ""
5 4 2 2 4 8

bash数组的另一个解决方案:

[ ~]$ echo $str|(read -a words; for word in "${words[@]}"; do echo -n "${#word} "; done; echo "")
5 4 2 2 4 8

假设通过“单词”表示由空格分隔的文本,这将按字面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

如果你想计算所有字符,而不仅仅是字母,那就是:

$ 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

或者,将句子放在一个名为sentence的文件中:

$ awk '{for (i=1;i<=NF;i++) {printf " " length($i)}; print "" }' sentence
 5 4 2 2 4 9

如果我们想要删除前导空格:

$ 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM