【leetcode~Shell】:Tenth Line

【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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值