Basically, piping a command or block of text to something like: tail -n 3
(for example), will print only the last three lines to stdout
. Is there an equivalent, or similar method for doing the exact inverse of that? So that, in this example, it would print all but the last three lines to stdout
.
Asked
Active
Viewed 1,042 times
1

voices
- 1,272
2 Answers
1
Based on @don_crissti's comment; if you found this helpful, please upvote his comment.
If I have file a
containing:
1
2
3
4
5
6
7
8
9
10
and I want to get all but the last three lines I can run head -n -3
on it to produce the following:
# head -n -3 a
1
2
3
4
5
6
7

Alexej Magura
- 4,466
- 7
- 26
- 39
0
A way to do it could be something like this(not very elegant but tested it and it works):
a=$(wc -l <file.txt);a=$((a-3));sed ''$a'q;' file.txt
wc -l returns the number of the lines of the file. The number of the lines is now assigned to a.
since we want all but the last 3 lines, we are reducing a and then using sed to print until the ath line of the file.

spk
- 123
-
-
@don_crissti Nice one, I edited my answer with your suggestion. Cheers! :) – spk Jan 30 '17 at 23:12
-n -3
with-3
(which is equivalent to-n 3
. – jordanm Jan 30 '17 at 22:46head
like that. Conversely,tail
doesn't seem to accept negatives in the same way. If you want to go ahead and stick it in an answer, I'll mark it solved. – voices Jan 30 '17 at 22:55