码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 上的 bash 程序

时间:2015-04-20 20:42:45      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

leetcode 上的 bash 程序

leetcode 上的 bash 程序

注: 以下程序大部份从 leetcode 的讨论上看来的...

Tenth Line

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

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10

Your script should output the tenth line, which is:

Line 10

awk ‘NR == 10‘ file.txt

sed -n ‘10p‘ file.txt

cat file.txt | for i in `seq 1 10`; do read line; [ $i -eq 10 ] && echo $line; done

for i in `seq 1 10`; do read line; [ $i -eq 10 ] && echo $line; done < file.txt

tail -n+10 file.txt|head -1

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:

name age
alice 21
ryan 30

Output the following:

name alice ryan
age 21 30

ncol=`head -n1 file.txt | wc -w`
for i in `seq 1 $ncol`; do
    echo `cut -d‘ ‘ -f$i file.txt`
done

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:

987-123-4567
123 456 7890
(123) 456-7890

Your script should output the following valid phone numbers:

987-123-4567
(123) 456-7890

grep -E ‘^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}\b‘ file.txt

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:

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

cat words.txt | tr -s ‘ ‘ ‘\n‘ | sort | uniq -c | sort -rn| awk ‘{print $2,$1}‘

cat words.txt | xargs -n 1 | sort | uniq -c | sort -rn| awk ‘{print $2,$1}‘

leetcode 上的 bash 程序

标签:

原文地址:http://www.cnblogs.com/sunznx/p/4442380.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!