Shell-整理的面试题及答案

简介

每天的重复工作感觉自己没有什么进步,在社会中的时间越长感觉到的压力越大,作为一个无法逃脱的社畜,能怎么办呢
以前还没有感觉到什么压力,随着年龄 工作 社会环境 心态的变化吧,感觉压力越来越大,自己也比较懒散
下面的shell题,也是从网上看到的,希望能增加自己的熟练度吧

shell

统计词频 将一个文本中的单词的出现频率统计出来

下面是从ssh配置文件中复制过来的一段,当作words.txt中的内容,
words.txt

The strategy used for options in the default sshd_config shipped with
OpenSSH is to specify options with their default value where
possible, but leave them commented. Uncommented options override the
default value.

你的脚本应当输出(以词频降序排列):

options 3
default 3
with 2
the 2
where 1
value. 1
value 1
used 1
Uncommented 1
to 1
them 1

  • 答案
awk  '{for(i=1;i<= NF;i++){words[$i]++}}END{for(w in words){print w,words[w]}}'  w.txt |sort -rn -k 2

for i in $(cat w.txt);do echo $i;done|sort |uniq -c|sort -rn|awk '{print $2,$1}'
统计合格的手机号码

w.txt
987-123-4567
123 456 7890
(123) 456-7890

grep -P '^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$' w.txt
转置文件

假设 file.txt 文件内容如下:

name age
alice 21
ryan 30

应当输出:

name alice ryan
age 21 30

awk '{
    for (i=1;i<=NF;i++){
        if (NR==1){
            res[i]=$i
        }
        else{
            res[i]=res[i]" "$i
        }
    }
}END{
    for(j=1;j<=NF;j++){
        print res[j]
    }
}' file.txt

作者:gao-si-huang-bu
链接:https://leetcode-cn.com/problems/transpose-file/solution/awkming-ling-yong-shu-zu-chu-cun-dai-shu-chu-jie-g/
来源:力扣(LeetCode)

网站

leetcode

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章