192堕花、詞頻統(tǒng)計(jì)
寫一個(gè) bash 腳本以統(tǒng)計(jì)一個(gè)文本文件 words.txt 中每個(gè)單詞出現(xiàn)的頻率。
為了簡單起見,你可以假設(shè):
words.txt只包括小寫字母和 ' ' 。
每個(gè)單詞只由小寫字母組成。
單詞間由一個(gè)或多個(gè)空格字符分隔焚廊。
示例:
假設(shè) words.txt 內(nèi)容如下:
the day is sunny the the
the sunny is is
你的腳本應(yīng)當(dāng)輸出(以詞頻降序排列):
the 4
is 3
sunny 2
day 1
# Read from the file words.txt and output the word frequency list to stdout.
cat words.txt | xargs -n 1 | awk '{
if($1 in data)
data[$1] = data[$1] + 1
else
data[$1] = 1
} END {for(str in data) print data[str],str}' | sort -rn | awk '{print $2, $1}'
193、有效的電話號(hào)碼
給定一個(gè)包含電話號(hào)碼列表(一行一個(gè)電話號(hào)碼)的文本文件 file.txt习劫,寫一個(gè) bash 腳本輸出所有有效的電話號(hào)碼咆瘟。
你可以假設(shè)一個(gè)有效的電話號(hào)碼必須滿足以下兩種格式: (xxx) xxx-xxxx 或 xxx-xxx-xxxx。(x 表示一個(gè)數(shù)字)
你也可以假設(shè)每行前后沒有多余的空格字符诽里。
示例:
假設(shè) file.txt 內(nèi)容如下:
987-123-4567
123 456 7890
(123) 456-7890
你的腳本應(yīng)當(dāng)輸出下列有效的電話號(hào)碼:
987-123-4567
(123) 456-7890
# Read from the file file.txt and output all valid phone numbers to stdout.
awk "/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/" file.txt
194袒餐、轉(zhuǎn)置文件
給定一個(gè)文件 file.txt,轉(zhuǎn)置它的內(nèi)容。
你可以假設(shè)每行列數(shù)相同灸眼,并且每個(gè)字段由 ' ' 分隔.
示例:
假設(shè) file.txt 文件內(nèi)容如下:
name age
alice 21
ryan 30
應(yīng)當(dāng)輸出:
name alice ryan
age 21 30
# Read from the file file.txt and print its transposed content to stdout.
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
195卧檐、第十行
給定一個(gè)文本文件 file.txt,請只打印這個(gè)文件中的第十行焰宣。
示例:
假設(shè) file.txt 有如下內(nèi)容:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
你的腳本應(yīng)當(dāng)顯示第十行:
Line 10
# Read from the file file.txt and output the tenth line to stdout.
awk 'NR == 10{print $0}' file.txt