我需要從文本檔案中查找數字或重復字符,并且需要將檔案名作為引數傳遞。
示例:
test.txt資料包含
Zoom
輸出應該是這樣的:
z 1
o 2
m 1
我需要一個接受檔案名作為引數的命令,然后列出該檔案中的字符數。在我的示例中,我有一個包含zoom單詞的 test.txt。所以輸出就像每個字母重復了多少次。
我的嘗試:
vi test.sh
#!/bin/bash
FILE="$1" --to pass filename as argument
sort file1.txt | uniq -c --to count the number of letters
uj5u.com熱心網友回復:
只是猜測?
cat test.txt |
tr '[:upper:]' '[:lower:]' |
fold -w 1 |
sort |
uniq -c |
awk '{print $2, $1}'
m 1
o 2
z 1
uj5u.com熱心網友回復:
建議awk計算各種字符的腳本:
awk '
BEGIN{FS = ""} # make each char a field
{
for (i = 1; i <= NF; i ) { # iteratre over all fields in line
charsArr[$i]; # count each field occourance in array
}
}
END {
for (char in charsArr) { # iterrate over chars array
printf("= %s\n", charsArr[char], char); # cournt char-occourances and the char
}
}' |sort -n
或者在一行中:
awk '{for(i=1;i<=NF;i ) arr[$i]}END{for(char in arr)printf("= %s\n",arr[char],char)}' FS="" input.1.txt|sort -n
uj5u.com熱心網友回復:
#!/bin/bash
#get the argument for further processing
inputfile="$1"
#check if file exists
if [ -f $inputfile ]
then
#convert file to a usable format
#convert all characters to lowercase
#put each character on a new line
#output to temporary file
cat $inputfile | tr '[:upper:]' '[:lower:]' | sed -e 's/\(.\)/\1\n/g' > tmp.txt
#loop over every character from a-z
for char in {a..z}
do
#count how many times a character occurs
count=$(grep -c "$char" tmp.txt)
#print if count > 0
if [ "$count" -gt "0" ]
then
echo -e "$char" "$count"
fi
done
rm tmp.txt
else
echo "file not found!"
exit 1
fi
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/451501.html
