英文原文
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.
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.
中文题目
给定一个文本文件 file.txt
,请只打印这个文件中的第十行。
示例:
假设 file.txt
有如下内容:
Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10
你的脚本应当显示第十行:
Line 10
说明:
1. 如果文件少于十行,你应当输出什么?
2. 至少有三种不同的解法,请尝试尽可能多的方法来解题。
通过代码
高赞题解
以下三种方式均可以运行通过:
grep -n "" file.txt | grep -w '10' | cut -d: -f2
sed -n '10p' file.txt
awk '{if(NR==10){print $0}}' file.txt
但是考虑到说明中行数不足10的情况处理,可以做如下处理:
row_num=$(cat file.txt | wc -l)
echo $row_num
if [ $row_num -lt 10 ];then
echo "The number of row is less than 10"
else
awk '{if(NR==10){print $0}}' file.txt
fi
其中文件行数row_num
可以使用如下几种方式获取
awk '{print NR}' file.txt | tail -n1
10
awk 'END{print NR}' file.txt
10
grep -nc "" file.txt
10
grep -c "" file.txt
10
grep -vc "^$" file.txt
10
grep -n "" file.txt|awk -F: '{print '}|tail -n1 | cut -d: -f1
10
grep -nc "" file.txt
10
sed -n "$=" file.txt
10
wc -l file.txt
10 file.txt
cat file.txt | wc -l
10
wc -l file.txt | cut -d' ' -f1
10
感觉nice的点个赞再走,详细介绍可以看我的一篇文章:LeetCode上仅有的4道shell编程题解析
统计信息
通过次数 | 提交次数 | AC比率 |
---|---|---|
37329 | 85309 | 43.8% |
提交历史
提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
---|