来源:老男孩博客  http://oldboy.blog.51cto.com/2561410/1632876

范例

企业面试题20(中企动力)::用shell处理以下内容

1、按单词出现频率降序排序!

2、按字母出现频率降序排序!

the squid project provides a number of resources toassist users design,implement and support squid installations. Please browsethe documentation and support sections for more infomation



第一问解答:

[root@LAMP ~]# echo "the squid project provides a number of resources toassist users design,implement and support squid installations. Please browsethe documentation and support sections for more infomation

" > a.log

[root@LAMP ~]# cat a.log|tr " " "\n "|sort|uniq -c |sort -rn

      2 support

      2 squid

      2 and

      1 users

      1 toassist

      1 the

      1 sections

      1 resources

      1 provides

      1 project

      1 of

      1 number

      1 more

      1 installations.

      1 infomation

      1 for

      1 documentation

      1 design,implement

      1 browsethe

      1 a

      1 Please

##############################################

第二问解答


[root@LAMP ~]# cat a.log |sed 's/./&\n/g'|sort|uniq -c|sort -rn

     23  

     19 s

     17 e

     16 o

     14 t

     12 n

     12 i

     11 r

      9 a

      8 u

      7 p

      7 d

      6 m

      4 l

      4 c

      3 f

      2 q

      2 h

      2 b

      1 w

      1 v

      1 j

      1 g

      1 P

      1 .

      1 ,

      1 

[root@LAMP ~]


解答思路来源:

echo lvnianabcde | awk -F '' '{for(i=1;i<=NF;i++)print $i}'

echo lvnianabcde | sed 's/./&\n/g'

echo lvnianabcde | grep -Po '.'

echo lvnianabcde | grep -o '.'

echo lvnianabcde | fold  -w1  

 

###########################################################################

###########################################################################

###########################################################################

http://oldboy.blog.51cto.com/2561410/1687026

假如现在有个文本,格式如下:

a  1

b  3

c  2

d  7

b  5

a  3 

g  2

f  6

d  9

即左边是随机字母,右边是随机数字,要求写个脚本使其输出格式为:

a  4

b  8

c  2

d  16

f  6

g  2

即将相同的字母后面的数字加在一起,按字母的顺序输出。

解答

[root@KEEP2 dd]# cat oldboy1.log 

a  1

b  3

c  2

d  7

b  5

a  3 

g  2

f  6

d  9

[root@KEEP2 dd]# 

[root@KEEP2 dd]# cat oldboy1.log |awk '{a[$1]+=$2}END{for(i in a){print i,a[i]}}' 

a 4

b 8

c 2

d 16

f 6

g 2

[root@KEEP2 dd]#