簡體   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