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

时间:2014-03-23 21:41:43

标签: bash awk io

嘿所有,所以我正在编写一个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

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

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

仅使用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

答案 2 :(得分:1)

假设“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

答案 3 :(得分:0)

$ 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