Reputation: 363
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.
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.
$>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?
$>head -n 4 file.txt | tail -n +4
Upvotes: 0
Views: 4181
Reputation: 52374
From the man page:
-n, --lines=[+]NUM output the last NUM lines, instead of the last 10; or use -n +NUM to output starting with line 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.
Upvotes: 2
Reputation: 3203
tail
command also comes with an +
option which is not present in the head command. With this option tail command prints, the data starting from the specified line number of the file instead of the end.
For command: tail +n file_name
, data will start printing from line number n
till the end of the file
Let's say we have file 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 :
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 :
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
+
and -
both have a different meaning in tail
.
Upvotes: 2