I want to understand the following command in Linux:
# tail -n+454 /path/to/a/file | head -n 6
I expect that tail -n+454 /path/to/a/file
prints the lines, starting at line 454 and the following 5 lines.
The |
sends that output tohead
as an input. Then only the first 10 lines are taken.
Finally, -n 6
defines that only the first 6 lines are printed to the screen.
Did I translate the command correctly?
Now I have the following problem: Let's assume I have a file and the following line in it:
# Step #6: Configure output plugins
I want to print the 5 lines immediately before that line (including that line).
First I checked, what line number my line in question has:
nl /path/to/a/file | grep output
The line number is 459.
I want the 5 lines preceding line 459 as well as line 459 itself (that is, line 454 to 459).
The command tail -n+454 /path/to/a/file | head -n 6
gives me the following output:
...and this is line 380 to 384:
I expected to get lines 454 to 459. What did I not understand? Is my command not correct?
The mistake I made was that I displayed only the non-empty lines in the file, which was wrong.
It's better to use...
nl -ba [FILE]
to number all lines in the file. Then look up the lines of interest and use the head and tail commands (with piping) to get the final results.
Example:
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
All commands lead to the same result.
Another mistake I made was the syntax. There should be a space between -n and +NUM.
By the way, the line numbers in my OP are wrong, because I used the wrong numbering line command. The line I refer to is 544 not 459.