LeetCode刷题笔记——Shell

195. Tenth Line

我想到的方法:

1
2
3
4
5
6
7
lines=$(cat file.txt | wc -l)
if $(test ${lines} -lt 10);
then
echo ""
else
head -10 file.txt | tail -n 1
fi

大神的解法们:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Solution 1
cnt=0
while read line && [ $cnt -le 10 ]; do
let 'cnt = cnt + 1'
if [ $cnt -eq 10 ]; then
echo $line
exit 0
fi
done < file.txt

# Solution 2
awk 'FNR == 10 {print }' file.txt
# OR
awk 'NR == 10' file.txt

# Solution 3
sed -n 10p file.txt

# Solution 4
tail -n+10 file.txt|head -1

本站总访问量