计数名称以文件中的特定字符开头

时间:2010-11-24 02:00:33

标签: shell

我有以下文件::

FirstName, FamilyName, Address, PhoneNo

文件是根据姓氏排序的,我如何计算以特定字符开头的姓氏数???

输出应该如下所示::

A: 2
B: 1
...

...

6 个答案:

答案 0 :(得分:2)

使用awk:

awk '{print substr($2, 1, 1)}' file|
  uniq -c|
  awk '{print $2 ": " $1}'

好的,没有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)

答案 1 :(得分:1)

while read -r f l r; do echo "$l"; done < inputfile | cut -c 1 | sort | uniq -c

答案 2 :(得分:1)

只是壳牌

#! /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

<强>运行

frayser@gentoo ~/doc/Answers/src/SH/names $ sh names.sh
A : 1
F : 2
H : 3
K : 1
frayser@gentoo ~/doc/Answers/src/SH/names $ 

要从文件中读取,请删除此处的文档,然后运行:

chmod +x names.sh
./names.sh <file

答案 3 :(得分:0)

“艰难的方式” - 没有使用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

答案 4 :(得分:0)

awk one-liner:

awk '
    {count[substr($2,1,1)]++} 
    END {for (init in count) print init ": " count[init]}
' filename

答案 5 :(得分:0)

打印每个字母开头的单词数:

for i in {a..z};做echo -n“$ i:”; find path / to / folder -type f -exec sed“s / / \ n / g”{} \; | grep ^ $ i | wc -c | awk'{print $ 0}';完成

相关问题