56 - 第十行
题目
给定一个文本文件 file.txt,请只打印这个文件中的第十行。
示例:
假设 file.txt 有如下内容:
Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10
你的脚本应当显示第十行:
Line 10
说明:
如果文件少于十行,你应当输出什么?
至少有三种不同的解法,请尝试尽可能多的方法来解题。
解答
awk
Runtime: 0 ms, faster than 100.00% of Bash online submissions forTenth Line.
Memory Usage: 3.7 MB, less than 42.86% of Bash online submissions for Tenth Line.
关键这个awk
是啥意思呢
awk就是把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再进行各种分析处理。
所以这句话就是,从file.txt
里面一行行读取内容,读取到第十行,展示出来。
grep 适合单纯的查找或匹配文本
sed 适合编辑匹配到的文本
awk 适合格式化文本,对文本进行较复杂格式处理
head/tail
Runtime: 8 ms, faster than 6.13% of Bash online submissions for Tenth Line.
Memory Usage: 3.6 MB, less than 100.00% of Bash online submissions for Tenth Line.
tail -n +10 file.txt
,意思是读取file.txt
10行以后的内容|
是将前面代码的结果,来作为后面代码的输入
换言之这句话,先读取10行以后内容,再从结果中取第一行。就是第十行的内容了。
sed
Runtime: 4 ms, faster than 72.91% of Bash online submissions for Tenth Line.
Memory Usage: 3.7 MB, less than 85.71% of Bash online submissions for Tenth Line.
10p
,打印第十行,小写p表名打印模版块的行
Last updated
Was this helpful?