leetcode上的Shell题汇总

正则三剑客:sed,awk,grep

  1. 统计词频

https://leetcode-cn.com/problems/word-frequency/

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

cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -rn | awk '{print $2, $1}'
  1. 有效电话号码

https://leetcode-cn.com/problems/valid-phone-numbers/

sed -n -r '/^([0-9]{3}-|([0-9]{3}) )[0-9]{3}-[0-9]{4}$/p' file.txt

grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt
  1. 转置文件

https://leetcode-cn.com/problems/transpose-file/

awk '{
    for (i = 1; i <= NF; ++i) {
        if (NR == 1) s[i] = $i;
        else s[i] = s[i] " " $i;
    }
} END {
    for (i = 1; s[i] != ""; ++i) {
        print s[i];
    }
}' file.txt
  1. 第十行

https://leetcode-cn.com/problems/tenth-line/

awk 'NR==10' file.txt

sed -n '10p' file.txt

tail -n +10 file.txt  | head -n 1

你可能感兴趣的:(LeetCode刷题练习,shell编程,leetcode做题代码合集)