head 将输出文件中的前 n 行,tails 将输出文件中的后 n 行。
假设您想输出文件的第 4 行,下面的命令将执行此操作,这对我来说很有意义,因为前 4 行通过管道传输到 tails,然后 tails 将输出最后 1 行,因此第 4 行将是输出。
$>head -n 4 file.txt | tail -n 1
但是,下面的命令将产生相同的结果,但我无法理解为什么它会产生相同的结果。 +4部分有什么作用?
$>head -n 4 file.txt | tail -n +4
最佳答案
tail
命令还附带 +
head 命令中不存在的选项。使用此选项 tail 命令将打印从文件的指定行号开始而不是结尾的数据。
对于命令:tail +n file_name
,数据将从行号n
开始打印直到文件末尾
假设我们有文件 file.txt
Hello from localhost1
Hello from localhost2
Hello from localhost3
Hello from localhost4
Hello from localhost5
Hello from localhost6
如果您将 tail 与 +
一起使用然后选择 tail
将从指定的数字开始,如下所示:
head -n 4 file.txt | tail -n +1
Hello from localhost1
Hello from localhost2
Hello from localhost3
Hello from localhost4
从第二行开始:
head -n 4 file.txt | tail -n +2
Hello from localhost2
Hello from localhost3
Hello from localhost4
从第三行开始:
head -n 4 file.txt | tail -n +3
Hello from localhost3
Hello from localhost4
从第四行开始:
head -n 4 file.txt | tail -n +4
Hello from localhost4
这就是它提供与 head -n 4 file.txt | tail -n 1
相同的输出的原因。
+
和-
两者在 tail
中有不同的含义.
关于linux - 使用 Linux 命令 head 和 tail,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57932690/