Blogs Hub

by Sumit Chourasia | Oct 16, 2020 | Category :coding | Tags : algorithm bash data-structure easy leetcode

Tenth Line - Bash - Easy - LeetCode

Tenth Line - Bash - Easy - LeetCode

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.

# Read from the file file.txt and output the tenth line to stdout.
awk 'FNR == 10 {print }'  file.txt

 

From an efficiency standpoint, wouldn't you want to exit once you've printed the 10th line?

The awk and sed solutions do not exit immediately after printing. So in case of a large file, they will print the 10th line, but then keep on looping until the end of file.

For my testcase, I created a file that has 100 million lines. And then I use the "time" command to time each solution. Notice that Solutions 1 and 4 are very fast - less than a second, but solutions 2 and 3 take up anywhere from 12 to 19 seconds, which is an unnecessary time hog.

The last two awk scripts exit right after printing and you can see that their run times have improved.
I don't know the equivalent for sed.

(Also, I replaced the "exit 0" in the shell script by a "return", which returns control to the shell prompt but does not close the terminal window.)

Contributed By: Sumit Chourasia
Combination Sum II - Array - Medium - LeetCode
Contributed By: Sumit Chourasia
Triangle - Array - Medium - LeetCode
Contributed By: Sumit Chourasia
Maximum Swap - Array - Medium - LeetCode