下面哪些命令可以查看file1文件的第300-500行的内容?

下面哪些命令可以查看file1文件的第300-500行的内容?

cat file1 | tail -n +300 | head -n 200
cat file1| head -n 500 | tail -n +300
sed -n '300,500p' file1

答案:BC

解释:

>head --help
# head -n, --lines=[-]NUM       
# print the first NUM lines instead of the first 10;
# with the leading '-', print all but the last NUM lines of each file
意思就是
head -n k          # 打印前k行
head -n -k         # 打印除最后k行外的所有内容

>tail --help
# tail -n, --lines=[+]NUM       
# output the last NUM lines, instead of the last 10;
# or use -n +NUM to output starting with line NUM
意思就是
tail -n k          # 打印最后k行
tail -n +k         # 从第k行开始打印

回到这道题,输出300行-500行的内容。

A选项:从第300行开始,接着输出前200行的内容,但这里的200行包括了第300行,不包括第500行。所以应该改为cat file1 | tail -n +300 | head -n 201

B选项:先取出前500行,再从300行开始。 cat file1 | head -n 500 | tail -n + 300 ,正确。

C选项:sed命令 p :列印,将某个选择的数据印出。通常 p 会与参数 sed -n 一起运行

sed -n '300-500p' file1 打印300-500行,正确。

亲自测试,A输出300-499;BC输出300-500

原文地址:https://www.cnblogs.com/chenjo/p/14998862.html