linux - 使用 Linux 命令 head 和 tail

标签 linux shell unix sh

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/

相关文章:

shell - 从 UEFI 应用程序内部运行 UEFI shell 命令

linux - 多个线程定期更新全局变量,而第三个线程等待读取

javascript - 在没有 npm 的情况下使用 socket.io 和 express 模块

linux - rsync 不复制我的文件

c - UNIX:recv 的内存问题 - malloc.c:3096:sSYSMALLOC:断言

c++ - ASIO 库 - 未调用处理程序

linux - 如果两个目录共有,则更新文件;如果在一个目录中唯一,则删除该文件

linux - 当在ARM上预取更多数据时,为什么高速缓存未命中会发生更多?

c - 在 C 中的 main 中返回负值

linux - 将长标准输出管道传输到 tee 命令有时会导致截断