LeetCode上shell一共就四題,但涉及的知識點可不少,有tr、grep、awk、sed等等,非常值得練練手,希望LeetCode官方能多提供一些shell練習,畢竟shell是一名C++程式員的童子功呀!
目錄
LeetCode.192.統計詞頻
LeetCode 193.有效的電話號碼
LeetCode 194.轉置檔案
LeetCode 195.第十行
LeetCode.192.統計詞頻

cat words.txt | tr -s ' ' '\n'|sort|uniq -c |sort -r|awk '{print $2" "$1}'
cat ——瀏覽檔案
tr -s ——替換字串(空格換為換行)保證了一行一個單詞
sort ——默認ASCII值排序,排序號后還會有重復
uniq —— 去重,-c再輸出重復次數,結果就是 ”4 abc“ abc出現了4次
sort -r —— 反向排序,也就是從大到小,得到按頻率高低的結果
awk ——格式化輸出,規定輸出是先字串再重復次數,所以先$2再$1,中間空格分隔
LeetCode 193.有效的電話號碼

# Read from the file file.txt and output all valid phone numbers to stdout.
cat file.txt | grep -P '^(\d{3}-\d{3}-\d{4})$|^(\(\d{3}\) \d{3}-\d{4})$'
LeetCode 194.轉置檔案

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

# Read from the file file.txt and output the tenth line to stdout.
awk 'NR == 10' file.txt
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/278811.html
標籤:其他
