1.Word Frequency 统计词频
【Shell|Shell leecode】For example, assume that words.txt
has the following content:
the day is sunny the the
the sunny is is
Your script should output the following, sorted by descending frequency:
the 4
is 3
sunny 2
day 1
# Read from the file words.txt and output the word frequency list to stdout.
awk '{i=1;
while(i<=NF) {print $i;
i++}}'words.txt | sort | uniq -c | sort -k1nr | awk '{print $2 " " $1}'
2. Valid Phone Numbers 正则判断是否有效 For example, assume that file.txt
has the following content:
987-123-4567
123 456 7890
(123) 456-7890
Your script should output the following valid phone numbers:
987-123-4567
(123) 456-7890
# Read from the file file.txt and output all valid phone numbers to stdout.
cat file.txt | grep -Eo '^((\([0-9]{3}\)\s)|([0-9]{3}-))[0-9]{3}-[0-9]{4}$'
3. Transpose File 转置文件 For example, if file.txt
has the following content:
name age
alice 21
ryan 30
Output the following:
name alice ryan
age 21 30
# Read from the file file.txt and print its transposed content to stdout.
awk '{
for( i=0;
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
4. Tenth Line 输出第10行
# Read from the file file.txt and output the tenth line to stdout.
awk '{ if(NR == 10) print $0 }' file.txt