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.
用Bash脚本来打印一个txt文件的第十行。
1. awk是强大的文本分析工具,具有流控制、数学运算、进程控制、内置的变量和函数、循环和判断的功能。其中NR表示行数,$0表示当前记录
awk '{if(NR == 10) print $0}' file.txt
# OR
awk 'FNR == 10 {print }' file.txt
# OR
awk 'NR == 10' file.txt
2. 使用流编辑工具sed来做。-n默认表示打印所有行,p限定了具体打印的行数
sed -n 10p file.txt
3. 使用tail和head关键字来打印。head表示从头开始打印,tail表示从结尾开始打印,'-' 表示根据文件行数进行打印。例如:
tail -n 3 file.txt: 打印file文件的最后三行内容
tail -n +3 file.txt: 从file文件第三行开始打印所有内容
head -n 3 file.txt: 打印file文件的前三行
head -n -3 file.txt: 打印file文件除了最后三行的所有内容
竖杠|为管道命令,用法: command 1 | command 2 , 把第一个命令command1执行的结果作为command 2的输入传给command 2。
tail -n +10 file.txt | head -n 1
or
head -n 10 file.txt | tail -n +10
4. 编写函数
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
All LeetCode Questions List 题目汇总
来源:oschina
链接:https://my.oschina.net/u/4393984/blog/3795832