2015-12-30 100 views
1

是否有計算字符在命令行unix中出現的字符串的次數?統計unix中某個字符出現在字符串中的次數

例如:字符串= 「你好」, 「升」 這應該返回2

字符串= 「你好」 的 「k」 這應該返回0

字符串= 「你好」, 「H」 此應該返回0

感謝

+0

'sed'和'wc'可以工作。 – user2864740

+0

> grep -o「。」 <<< 「hello.txt的。」 | wc -l輸出返回10,這是不正確的。理想情況下,這應該返回2 – sunshine737

+0

您正在爲「。」,這是一個匹配任何字符的正則表達式。如果要匹配「點」字符,請嘗試使用'grep -o「\。」'代替 –

回答

1

我在$ STRING尋找字符:

echo $STRING| grep -o I | wc -l 

strippedvar=${string//[^l]/} 
echo "char-count: ${#strippedvar}" 

首先您從L個不同的所有字符出來的字符串:

0

使用與字符串Hello和尋找「L」猛砸建宏是可以做到的。
您顯示剩餘變量的長度。

在替代的lettter可以由VAR給出,如圖此循環:

string=hello 
for ch in a b c d e f g h i j k l m; do 
    strippedvar=${string//[^$ch]/} 
    echo "The letter ${ch} occurs ${#strippedvar} times" 
done 

OUTPUT:

The letter a occurs 0 times 
The letter b occurs 0 times 
The letter c occurs 0 times 
The letter d occurs 0 times 
The letter e occurs 1 times 
The letter f occurs 0 times 
The letter g occurs 0 times 
The letter h occurs 1 times 
The letter i occurs 0 times 
The letter j occurs 0 times 
The letter k occurs 0 times 
The letter l occurs 2 times 
The letter m occurs 0 times 
相關問題