Tenth Line - Bash - Easy - LeetCode
💻 coding

Tenth Line - Bash - Easy - LeetCode

1 min read 256 words
1 min read
ShareWhatsAppPost on X
  • 1To print the 10th line of a file, use the command 'awk 'FNR == 10 {print }' file.txt'.
  • 2If the file has fewer than 10 lines, no output should be generated.
  • 3Efficient solutions exit after printing the 10th line, significantly reducing runtime on large files.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"To print the 10th line of a file, use the command 'awk 'FNR == 10 {print }' file.txt'."

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

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 16 October 2020 · 1 min read · 256 words

Part of AskGif Blog · coding

You might also like