Solutions, Leetcode Shell Problems

Contents
  1. 1. 193. Valid Phone Numbers
  2. 2. 195. Tenth Line
  3. 3. 192. Word Frequency
  4. 4. 194. Tranpose File

Last Modified: 2017-08-25 10:53:10

  • 193. Valid Phone Numbers
  • 195. Tenth Line
  • 192. Word Frequency
  • 194. Tranpose File

193. 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)

1
2
# Read from the file file.txt and output all valid phone numbers to stdout.
grep -E '^(([0-9]{3}-[0-9]{3}-[0-9]{4})|(\([0-9]{3}\) [0-9]{3}-[0-9]{4}))$' file.txt

195. Tenth Line

How would you print just the 10th line of a file?

1
2
3
4
5
6
7
8
9
# Read from the file file.txt and output the tenth line to stdout.
line_num=0
while read line && ((line_num < 10)); do
line_num=$line_num+1
if ((line_num == 10)); then
echo $line
break
fi
done < file.txt

192. Word Frequency

1
2
3
4
5
6
7
8
9
# Read from the file words.txt and output the word frequency list to stdout.
declare -A freq
while read word; do
((++freq[$word]))
done < <(tr -s " " "\n" < words.txt)
# echo ${words[*]}
for word in ${!freq[*]}; do
echo $word ${freq[$word]}
done | sort -k 2nbr

it seems that there some problems with shell array…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
➜ ~ a+=1
➜ ~ a+=1
➜ ~ echo ${a[*]}
11
➜ ~ for i in ${a[*]}; do
for> echo $i
for> done
11
➜ ~ for i in ${a[@]}; do
for> echo $i
for> done
11
➜ ~ for i in "${a[@]}"; do
for> echo $i
for> done
11
➜ ~ for i in "${a[*]}"; do
for> echo $i
for> done
11
➜ ~ echo ${a[1]}
1
➜ ~ echo ${a[2]}
1
➜ ~ echo 'num of elemets='${#a[*]}
num of elemets=2
# it looks rather werid... so avoid using it...

194. Tranpose 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:

1
2
3
4
5
6
7
name age
alice 21
ryan 30
# Output the following:
name alice ryan
age 21 30

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Read from the file file.txt and print its transposed content to stdout.
awk '
{
for(i = 1; i <= NF; ++i) {
if(1 == NR) {
s[i] = $i;
}
else {
s[i] = s[i] " " $i
}
}
}
END {
for(i = 1; s[i] != ""; ++i) {
print s[i];
}
}' file.txt

1. 除非注明,本博文即为原创,转载请注明链接地址
2. 本博文只代表博主当时的观点或结论,请不要恶意攻击
3. 如果本文帮到了您,不妨点一下 下面分享到 按钮,让更多的人看到