1

This question already has an answer here:

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.

marked as duplicate by don_crissti, jordanm, G-Man, Gilles command-line Jan 30 '17 at 23:25

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • @don_crissti you are correct, I was confusing -n -3 with -3 (which is equivalent to -n 3. – jordanm Jan 30 '17 at 22:46
  • Nice one. Yeah that's what i was after. I didn't realize you could specify a negative integer as an argument to head 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. – tjt263 Jan 30 '17 at 22:55
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
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.

  • Shorter as wc -l <file.txt and faster as head -n $a file.txt – don_crissti Jan 30 '17 at 23:08
  • @don_crissti Nice one, I edited my answer with your suggestion. Cheers! :) – yaku Jan 30 '17 at 23:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.