[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

Hint:

1. If the file contains less than 10 lines, what should you output?

2. There's at least three different solutions. Try to explore all possibilities.

题目大意:

输出一个文件的第10行。

思考:

1. 如果文件包含内容不足10行,应该输出什么?

2. 有至少3种不同的解决方法,尝试列举所有的可能方案

Bash脚本:

解法一,使用awk

# Read from the file file.txt and output the tenth line to stdout.
awk 'NR == 10' file.txt

解法二,使用sed

# Read from the file file.txt and output the tenth line to stdout.
sed -n '10p' file.txt

解法三,组合使用tail与head

# Read from the file file.txt and output the tenth line to stdout.
tail -n+10 file.txt | head -n1

 

本文链接:http://bookshadow.com/weblog/2015/03/28/leetcode-tenth-line/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论