问题描述
我想了解Linux中的以下命令:
# tail -n+454 /path/to/a/file | head -n 6
我希望 tail -n+454 /path/to/a/file
打印行,从第 454 行和接下来的 5 行开始。
|
将该输出作为输入发送到head
。然后只取前 10 行。
最后,-n 6
定义只有前 6 行被打印到屏幕上。
我是否正确翻译了命令?
# Step #6: Configure output plugins
我想打印该行之前的 5 行(包括该行)。
首先我检查了我有问题的行的行号:
nl /path/to/a/file | grep output
行号是 459。
我想要第 459 行之前的 5 行以及第 459 行本身(即第 454 行到第 459 行)。
命令 tail -n+454 /path/to/a/file | head -n 6
给了我以下输出:
...这是第 380 到 384 行:
我希望得到第 454 到 459 行。我不明白什么?我的命令不正确吗?
解决方法
使用这个命令:
head -n $(grep -n "Step #6: Configure output plugins" /path/to/a/file | awk -F ':' '{print $1}') /path/to/a/file | tail -n 5
注意:
该命令有两部分
a) 找到行号:
grep -n "Step #6: Configure output plugins" /path/to/a/file | awk -F ':' '{print $1}'
b) 您想要的过滤器行:
head -n [LINE NUMBER] /path/to/a/file | tail -n 5
,
我犯的错误是我只显示文件中的非空行,这是错误的。
最好使用...
nl -ba [FILE]
对文件中的所有行进行编号。然后查找感兴趣的行并使用 head 和 tail 命令(带管道)得到最终结果。
示例:
tail -n +539 [FILE] | tail -n 6
tail -n +539 [FILE] | head -n -212
head -n 544 [FILE] | tail -n 6
head -n 544 [FILE] | tail -n +539
所有命令都会导致相同的结果。
我犯的另一个错误是语法。 -n 和 +NUM 之间应该有一个空格。
顺便说一下,我的 OP 中的行号是错误的,因为我使用了错误的编号行命令。我指的是 544 而不是 459。