如何計算字串中空白的數目? - Linux

Table of Contents

請問在 shell script 中,
如何計算字串中空白的數目?

例如
"a bc d e" 應該有四個
" abc d " 應該有五個

--

All Comments

Odelette avatarOdelette2012-08-19
我剛剛玩了一下計算文件中空白的方式,我用的是sed + wc
Edwina avatarEdwina2012-08-21
cat test.txt | sed 's/[^ \t]//g' | wc -c
把非' ', '\t'清掉再計算字元數,不過會多計一個EOF
Gary avatarGary2012-08-26
cat test.txt | sed 's/[ \t]/1 /g' | wc -w
Gary avatarGary2012-08-30
上面打錯..我想說的是進一部再把把空白換成字串計word數即可
Connor avatarConnor2012-09-02
(但這樣就有點畫蛇添足,減一還比較乾脆)
Kumar avatarKumar2012-09-06
用php/perl/C來解決比較快,拔釘子用鉗子比用起子方便
Oscar avatarOscar2012-09-09
唯一的樂趣就是單行把他完成...XD
Olive avatarOlive2012-09-12
樓上應該去玩 Obfuscated C Code
Catherine avatarCatherine2012-09-16
google來的: echo "a bc d e" | grep -o ' ' | wc -l
Genevieve avatarGenevieve2012-09-19
推樓上
Olga avatarOlga2012-09-23
echo -n "a bc d e" | sed 's/[^ ]//g' | wc -c