Yifans_Z's Blog.

# LeetCode Shell 解题集合

2016/09/19 Share

LeetCode Shell 的试题多为文本操作，195. Tenth Line193. Valid Phone Numbers192. Word Frequency194. Transpose File 暂时只有4道题，就整合在这一起了
Shell 中文本处理的事情基本 awk sed grep sort uniq tail head 几个命令组合组合就搞定了

## 195. Tenth Line

### 大体意思

How would you print just the 10th line of a file?
For example, assume that file.txt has the following content:

Your script should output the tenth line, which is:

### 别人的解法

Reference: leetcode-195 Tenth Line - 2> /dev/null

## 193. Valid Phone Numbers

### 大体意思

Given a text file file.txt that contains list of phone numbers (one per line), write a one liner bash script to print all valid phone numbers.
You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit)
You may also assume each line in the text file must not contain leading or trailing white spaces.

For example, assume that file.txt has the following content:

Your script should output the following valid phone numbers:

### 别人的解法

Reference: LeetCode 193: Valid Phone Numbers – Revo

## 192. Word Frequency

### 大体意思

Write a bash script to calculate the frequency of each word in a text file words.txt.

For simplicity sake, you may assume:

words.txt contains only lowercase characters and space ' ' characters.
Each word must consist of lowercase characters only.
Words are separated by one or more whitespace characters.
For example, assume that words.txt has the following content:

Your script should output the following, sorted by descending frequency:

Note:
Don’t worry about handling ties, it is guaranteed that each word’s frequency count is unique.

### 别人的解法

1、利用 awk 默认一行一条记录，默认以空格划分每条记录，NF 为划分的总块数先打印出所有单词
2、排序 + 统计 + 消除重复
3、输出

## 194. Transpose File

### 大体意思

Given a text file file.txt, transpose its content.

You may assume that each row has the same number of columns and each field is separated by the ' ' character.

For example, if file.txt has the following content:

Output the following:

## 总结

Shell 中文本处理的事情基本 awk sed grep sort uniq tail head 几个命令组合组合就搞定了，各命令的常用方法之后总结