【leetcode~Shell】:Tenth Line
Tenth Line:https://leetcode.com/problems/tenth-line/
题意:打印出一个文件的第10行。
问题涉及到几个点:
1.如何读取一个文件?
2.如何找到第10行?
3.如果文件是空的或者少于10行怎么办?
4.有至少3种不同的解决方法,尝试列举所有的可能方案
解法1:
sed -n '10p' file.txt<span style="color: rgb(51, 51, 51); font-family: 'Courier New', Arial; font-size: 10pt; letter-spacing: 0.3px; line-height: 18px; white-space: pre-wrap; background-color: rgb(246, 246, 246);"> </span>
解法2:
awk <span class="hljs-string" style="box-sizing: border-box;">'NR == 10'</span> <span class="hljs-built_in" style="box-sizing: border-box;">file</span>.txt
注意: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 3 and 4 are very fast - less than a second, but solutions 1 and 2 take up anywhere from 12 to 19 seconds, which is an unnecessary time hog.
解法3:
tail -n+<span class="number">10</span> file.txt | head -n1<span style="font-family:Courier New, Arial;color:#333333;"><span style="font-size: 10pt; letter-spacing: 0.3px; line-height: 18px; white-space: pre-wrap; background-color: rgb(246, 246, 246);"> </span></span>
解法4:
cnt=1 while read line do if [ $((cnt)) == 10 ] ; then echo $line fi let cnt+=1 done < file.txt if [ $cnt -lt 10 ];then echo "" fi