How do I delete the last n lines of an ascii file using shell commands?
Asked
Active
Viewed 4.3k times
4
chaos
- 47,463
- 11
- 118
- 144
user137256
- 73
- 1
- 1
- 2
-
1@arved It's not a dublicate since this question is about the last **n** lines, not only the last line... – chaos Oct 06 '15 at 12:54
-
@chaos see this answer and replace 1 with n https://unix.stackexchange.com/a/52818/11472 – arved Oct 06 '15 at 12:56
-
@arved Pedantically it's not a dublicate, but I see your point. – chaos Oct 06 '15 at 12:57
-
@Gilles has [an answer there](http://unix.stackexchange.com/a/18815) – Stéphane Chazelas Oct 06 '15 at 13:01
3 Answers
13
With head (removes the last 2 lines):
head -n -2 file
With sed/tac (removes the last 2 lines):
tac file | sed "1,2d" | tac
tac reverses the file, sed deletes (d) the lines 1 to 2 (2 can be any number).
chaos
- 47,463
- 11
- 118
- 144
-
5Why is it when I try redirecting the output back into the file (OP asked to delete the lines of the file, after all), I just get a blanked file: `$ head -n -2 test-file > test-file` When I pick another file name, the `head` output redirects as I would expect? What's the best way to do the redirect into the same file? – user1717828 Oct 06 '15 at 13:37
-
5@user1717828 The problem is that `bash` processes the redirections first, then executes the command. When `>file` is processed bash creates (if not existing) an empty file, else it is truncated. `head` then prints nothing because the file it reads is empty. You have to go via a temporary file. `head -n -2 file >tmp && mv tmp file`. BTW: all tools which allow "inplace editing" (like `sed -i`, `gawk -i inplace`, `perl -i`) do exactly the same. – chaos Oct 06 '15 at 13:53
-
8`head -n -2` is great but is not supported by all versions of head, in particular the bsd version that ships with mac os :-( – phs Aug 04 '16 at 09:29
0
Have a look at the manpage for head - you can specify a number of lines, and it will give you that many lines out of a file.
head -10 filename
Gives first 10 lines of a file. If you don't know how long your file is, you can use wc -l to count the number of lines. And then use head to print the appropriate number.
Sobrique
- 4,404
- 14
- 24
-
-
`... | tee filename | sponge filename` can be valuable when you want to print it AND redirect it to a file. – Sridhar Sarnobat Aug 08 '19 at 22:11
-2
tac file| sed -i 'nd' | tac
tac reverses the file, sed deletes (d) the lines n numbers of lines
Anthon
- 78,313
- 42
- 165
- 222