shell简单练习

一、题目: 第十行  https://leetcode-cn.com/problems/tenth-line/

  给定一个文本文件 file.txt,请只打印这个文件中的第十行。

  说明:
    1. 如果文件少于十行,你应当输出什么?
    2. 至少有三种不同的解法,请尝试尽可能多的方法来解题。

  解法一:while循环

file=./file.txt
i=0
cat $file |
while read line
do
    ((i=i+1))
    if [ $i -eq 10 ];then
        echo $line
        break;
    fi
done

   解法二:用tail,head输出

#这种解法wa了,因为不到10行还是会输出最后1行
cat $'./file.txt' | head -n 10 | tail -n 1 
#可以从第10行开始输出,然后再输出第一行
tail -n +10 file.txt | head -1

  解法三:sed -n 查找

sed -n '10p' file.txt