我有以下文件::計數與特定字符開頭的文件
FirstName, FamilyName, Address, PhoneNo
文件根據姓氏排序,我怎麼能算姓氏的數量開始以特定字符?
輸出應該是這樣的:
A: 2
B: 1
...
?
我有以下文件::計數與特定字符開頭的文件
FirstName, FamilyName, Address, PhoneNo
文件根據姓氏排序,我怎麼能算姓氏的數量開始以特定字符?
輸出應該是這樣的:
A: 2
B: 1
...
?
使用awk:
awk '{print substr($2, 1, 1)}' file|
uniq -c|
awk '{print $2 ": " $1}'
OK,沒AWK。這裏有sed:
sed s'/[^,]*, \(.\).*/\1/' file|
uniq -c|
sed 's/.*\([0-9]\)\+ \([a-zA-Z]\)\+/\2: \1/'
好的,沒有sed。下面是使用Python:
import csv
r = csv.reader(open(file_name, 'r'))
d = {}
for i in r:
d[i[1][1]] = d.get(i[1][1], 0) + 1
for (k, v) in d.items():
print "%s: %s" % (k, v)
while read -r f l r; do echo "$l"; done < inputfile | cut -c 1 | sort | uniq -c
「硬辦法」 的要求—沒有用AWK或sed中的,正是對。如果您不確定這些命令中的任何一個是什麼意思,那麼您一定要查看每個命令的man page。
INTERMED=`mktemp` # Creates a temporary file
COUNTS_L=`mktemp` # A second...
COUNTS_R=`mktemp` # A third...
cut -d , -f 2 | # Extracts the FamilyName field only
tr -d '\t ' | # Deletes spaces/tabs
cut -c 1 | # Keeps only the first character
# on each line
tr '[:lower:]' '[:upper:]' | # Capitalizes all letters
sort | # Sorts the list
uniq -c > $INTERMED # Counts how many of each letter
# there are
cut -c1-7 $INTERMED | # Cuts out the LHS of the temp file
tr -d ' ' > $COUNTS_R # Must delete the padding spaces though
cut -c9- $INTERMED > $COUNTS_L # Cut out the RHS of the temp file
# Combines the two halves into the final output in reverse order
paste -d ' ' /dev/null $COUNTS_R | paste -d ':' $COUNTS_L -
rm $INTERMED $COUNTS_L $COUNTS_R # Cleans up the temp files
就在殼牌
#! /bin/bash
##### Count occurance of familyname initial
#FirstName, FamilyName, Address, PhoneNo
exec <<EOF
Isusara, Ali, Someplace, 022-222
Rat, Fink, Some Hole, 111-5555
Louis, Frayser, whaterver, 123-1144
Janet, Hayes, whoever St, 111-5555
Mary, Holt, Henrico VA, 222-9999
Phillis, Hughs, Some Town, 711-5525
Howard, Kingsley, ahahaha, 222-2222
EOF
while read first family rest
do
init=${family:0:1}
[ -n "$oinit" -a $init != "$oinit" ] && {
echo $oinit : $count
count=0
}
oinit=$init
let count++
done
echo $oinit : $count
運行
[email protected] ~/doc/Answers/src/SH/names $ sh names.sh
A : 1
F : 2
H : 3
K : 1
[email protected] ~/doc/Answers/src/SH/names $
從文件中讀取,刪除文件在這裏,然後運行:
chmod +x names.sh
./names.sh <file
AWK單行:
awk '
{count[substr($2,1,1)]++}
END {for (init in count) print init ": " count[init]}
' filename
打印多少字開始與每個字母:
對於i在{A..Z};做echo -n「$ i:」; find path/to/folder -type f -exec sed「s// \ n/g」{} \; | grep^$ i | wc -c | awk'{print $ 0}';完成
並且沒有awk,這怎麼做? – 2010-11-24 02:14:16
編輯,看看。 – 2010-11-24 02:19:47
並且沒有sed? :) – 2010-11-24 02:20:52