[Leetcode]195.tenth-line

题目

  1. Tenth Line

Given a text file file.txt, print just the 10th line of the file.

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

注意点

需要注意一下它提供的note,其实test也涵盖了note提到的两点:

Note:

  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.

尝试1

head -10 file.txt | tail -1

缺点是默认了文件必须大于等于十行。

  • 如果文件少于十行, head -10 file.txt会输出整个文件(比如它仅有的8行),tail -1之后获得对应的最后一行(比如第8行)。
195_1.png

解法1

head -n 10 file.txt | tail -n +10
  • head -n 10 file.txt: 得到前十行,或者整个文件(如果这个文件少于十行)。
  • tail -n +10: 得到从第十行以及它后面的所有。
   -n, --lines=[+]NUM
         output the last NUM lines, instead of the last 10; or use -n +NUM to output starting with line NUM

这样如果文件少于十行,不会输出最后一行,而是输出为

解法2

cat file.txt | sed -n '10p'
  • -n: 只显示对应的行数。若没有会输出全部
  • '10p': 中的p指print
   -n, --quiet, --silent
         suppress automatic printing of pattern space
   p      Print the current pattern space.
  number      Match only the specified line number (which increments  cumula‐
              tively  across  files, unless the -s option is specified on the
              command line).

解法3

cat file.txt | sed '10!d'
  • d: 指删除
   d      Delete pattern space.  Start next cycle.

解法4

这里有四种等价的使用awk的表达:

#awk example 1
cat file.txt | awk 'NR==10'
#awk example 2
cat file.txt | awk 'NR==10{print}'
#awk example 3
cat file.txt | awk '{if(NR==10) print}'
#awk example 4 完整版
cat file.txt | awk 'BEGIN{}; { if(NR==10) {print;} }; END{};' 

引用和推荐阅读:

https://leetcode.com/problems/tenth-line/

http://bigdatums.net/2016/02/22/3-ways-to-get-the-nth-line-of-a-file-in-linux/

https://leetcode.com/problems/tenth-line/discuss/55544/Share-four-different-solutions: 有一些奇怪的解法

该文章遵循创作共用版权协议 CC BY-NC 4.0,要求署名、非商业 、保持一致。在满足创作共用版权协议 CC BY-NC 4.0 的基础上可以转载,但请以超链接形式注明出处。文章仅代表作者的知识和看法,如有不同观点,可以回复并讨论。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 195 Tenth Line 第十行 Description:Given a text file file.txt...
    air_melt阅读 1,267评论 0 0
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,147评论 0 13
  • 1. Python的hello-world: print ("Hello, Python!")、 完了 摇就完事儿...
    LunarShade阅读 5,499评论 0 0
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 7,946评论 0 0
  • 茶如人生,沉时坦然,浮时荡然;苦和甜,清和涩。人生即是一本书,标题是开始,内容是经历,封皮亦是岁月的足迹。人生必有...
    南城以南_菜菜阅读 2,795评论 0 2