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

说明:

  1. 如果文件少于十行,你应当输出什么?

  2. 至少有三种不同的解法,请尝试尽可能多的方法来解题。

解答

awk

awk 'NR==10' file.txt

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是啥意思呢

https://www.cnblogs.com/ggjucheng/archive/2013/01/13/2858470.html

awk就是把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再进行各种分析处理。

参考网页中可以知道,NR是“已经读出的记录数,就是行号,从1开始”。

所以这句话就是,从file.txt里面一行行读取内容,读取到第十行,展示出来。

  • grep 适合单纯的查找或匹配文本

  • sed 适合编辑匹配到的文本

  • awk 适合格式化文本,对文本进行较复杂格式处理

head/tail

[参考](https://www.cocobolo.top/linux/2019/07/04/195.第十行(head&tail).html)

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

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.txt10行以后的内容

  • |是将前面代码的结果,来作为后面代码的输入

  • head -1是取第一行,相当于head -n 1

换言之这句话,先读取10行以后内容,再从结果中取第一行。就是第十行的内容了。

sed

sed -n 10p file.txt

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.

Last updated

Was this helpful?