代码改变世界

[LeetCode] 195. Tenth Line_Easy tag: Bash

2018-08-11 04:21  Johnson_强生仔仔  阅读(210)  评论(0编辑  收藏  举报

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:
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.

 

首先要去youtube上面找相关教程看....书到用时方恨少, 哭= =.
然后直到awk(line by line read)的基本用法, 如下:
1) awk '{print}' file.txt    => output all liles line by line
2) awk '/produce/ {print}' file.txt  => output all lines starts with produce
3) awk '/produce/ {print} $2' file.txt  => output all lines starts with produce 的第二个元素/word(空格为界限)
 
然后通过这个post, 我们得到NR, 和FNR的作用.

Awk NR gives you the total number of records being processed or line number. In the following awk NR example, NR variable has line number, in the END section awk NR tells you the total number of records in a file.

$ awk '{print "Processing Record - ",NR;}END {print NR, "Students Records are processed";}' student-marks
Processing Record -  1
Processing Record -  2
Processing Record -  3
Processing Record -  4
Processing Record -  5
5 Students Records are processed

Awk FNR Example: Number of Records relative to the current input file

When awk reads from the multiple input file, awk NR variable will give the total number of records relative to all the input file. Awk FNR will give you number of records for each input file.

$ awk '{print FILENAME, FNR;}' student-marks bookdetails
student-marks 1
student-marks 2
student-marks 3
student-marks 4
student-marks 5
bookdetails 1
bookdetails 2
bookdetails 3
bookdetails 4
bookdetails 5

In the above example, instead of awk FNR, if you use awk NR, for the file bookdetails the you will get from 6 to 10 for each record.

 

 

Code
awk 'NR== 10 {print}' file.txt
# or awk 'FNR== 10 {print}' file.txt