1

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.

voices
  • 1,272
  • @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. – voices Jan 30 '17 at 22:55

2 Answers2

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