LeetCode - Easy - 195. Tenth Line

浅浅的花香味﹌ 2022-12-30 08:17 166阅读 0赞

Topic

  • Bash

Description

https://leetcode.com/problems/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:

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

Your script should output the tenth line, which is:

  1. Line 10

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.

Analysis

  1. awk 是一种处理文本文件的语言,是一个强大的文本分析工具。
  2. sed 可依照脚本的指令来处理、编辑文本文件。
  3. tail 命令可用于查看文件的内容

Submission

  1. # Solution 1
  2. cnt=0
  3. while read line && [ $cnt -le 10 ]; do
  4. let 'cnt = cnt + 1'
  5. if [ $cnt -eq 10 ]; then
  6. echo $line
  7. exit 0
  8. fi
  9. done < file.txt
  10. # Solution 2
  11. awk 'FNR == 10 {print }' file.txt
  12. # OR
  13. awk 'NR == 10' file.txt
  14. # Solution 3
  15. sed -n 10p file.txt
  16. # Solution 4
  17. tail -n+10 file.txt|head -1

Test

发表评论

表情:
评论列表 (有 0 条评论,166人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Leetcode解题思路总结(Easy)

    近来走上了Leetcode刷题之路,不过刷题背后更重要的是思路,掌握了方法,举一反三融会贯通。故在此我总结每道题的解题思路,这篇博客只涵盖Easy模式的题目,并按照题目从简单到