简体   繁体   English

前后使用Linux命令

[英]Using Linux commands head and tail

head will output the first n amount of lines from a file and tails will output the last n amount of lines form a file. head将输出文件中的前n行,而tails将输出文件中的后n行。

Say you want to output the 4th line of the file, the below command will do just that and it makes sense to me because the first 4 lines is piped to tails which then tails will output the last 1 line therefore the 4th line will be the output. 假设您要输出文件的第4行,下面的命令就可以做到这一点,这对我来说很有意义,因为前4行通过管道连接到尾部,然后尾部将输出最后1行,因此第4行是输出。

$>head -n 4 file.txt | tail -n 1

However, this command below will produce the same results, but I can't comprehend why it produces the same results. 但是,下面的此命令将产生相同的结果,但是我无法理解为什么它会产生相同的结果。 What does the +4 part do? +4部分有什么作用?

$>head -n 4 file.txt | tail -n +4

From the man page : 手册页

-n, --lines=[+]NUM output the last NUM lines, instead of the last 10; -n,--lines = [+] NUM输出最后NUM行,而不是最后10行; or use -n +NUM to output starting with line NUM 或使用-n + NUM从NUM行开始输出

So tail -n +4 starts printing at the fourth line of the input, which in this case is the first four lines of the file, thus only printing the fourth line. 因此, tail -n +4在输入的第四行开始打印,在这种情况下,该行是文件的前四行,因此仅打印第四行。

tail command also comes with an + option which is not present in the head command. tail命令还带有一个+选项,该选项在head命令中不存在。 With this option tail command prints, the data starting from the specified line number of the file instead of the end. 使用此选项tail命令打印时,数据从文件的指定行号开始而不是结尾。

For command: tail +n file_name , data will start printing from line number n till the end of the file 对于命令: tail +n file_name ,数据将从行号n开始打印,直到文件末尾

Let's say we have file file.txt 假设我们有文件file.txt

Hello from localhost1
Hello from localhost2
Hello from localhost3
Hello from localhost4
Hello from localhost5
Hello from localhost6

If you will use tail with + option then tail will start from the specified number like below : 如果您将tail带+选项使用,那么tail将从指定的数字开始,如下所示:

head -n 4 file.txt | tail -n +1
Hello from localhost1
Hello from localhost2
Hello from localhost3
Hello from localhost4

Starts from 2nd line : 从第二行开始:

head -n 4 file.txt | tail -n +2
Hello from localhost2
Hello from localhost3
Hello from localhost4

Starts from 3rd line : 从第三行开始:

head -n 4 file.txt | tail -n +3
Hello from localhost3
Hello from localhost4

Starts from 4th line : 从第4行开始:

head -n 4 file.txt | tail -n +4
Hello from localhost4

That is the reason it's giving the same output as head -n 4 file.txt | tail -n 1 这就是为什么它提供与head -n 4 file.txt | tail -n 1相同的输出的原因head -n 4 file.txt | tail -n 1 head -n 4 file.txt | tail -n 1

+ and - both have a different meaning in tail . +-tail都有不同的含义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM