2014-01-19 35 views
1

我知道以下命令計算字符串變量中特定字符的數量。如何從使用shell的字符串逐字獲取

X = 「這是一個測試」

的grep -o 「S」 < < < 「$ X」 |廁所-l

我需要的是一個計數的字符串變量的單詞數,並得到所有的話一個接一個,在一個循環中的命令。

任何想法?提前致謝。

回答

1

使用bash數組:

x="This is a test" 
arr=($x) 

echo "No of words:" "${#arr[@]}" 
No of words: 4 

# to print all array elements 
printf "%s\n" "${arr[@]}" 
This 
is 
a 
test 

# to iterate the string word by word 
for w in "${arr[@]}"; do 
    echo "$w" 
done 
相關問題