Sign up ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I want to shrink a file's size by brute-force, that is, I don't care about the rest, I just want to cut the file, say by half, and discard the rest.

The first thing that comes to mind is Perl's truncate. I'm following the example on that page and did the exactly the same thing:

seq 9 > test.txt
ls -l test.txt
perl -we 'open( FILE, "< ./test.txt" ) && truncate( FILE, 8 ) && close(FILE);'

But the file still has the same size:

$ ls -lgG test.txt
-rw-rw---- 1 18 2013-08-08 09:49 test.txt

How can I make this work?

share|improve this question

2 Answers 2

up vote 18 down vote accepted
perl -we 'open( FILE, "< ./test.txt" ) && truncate( FILE, 8 ) && close(FILE);'

opens the file for reading. However, to truncate the file you need to modify it, so a read-only file handle isn't going to work. You need to use the "modify" mode ("+>").

As a side issue, it always amazes me when people let system calls fail silently and then ask what went wrong. An essential part of diagnosing a problem is looking at the error message produced; even if you don't understand it, it makes life much easier for those you ask for help.

The following would have been somewhat more helpful:

perl -we 'open(FILE, "<", "./test.txt") or die "open: $!";
          truncate(FILE, 8) or die "truncate: $!";

although admittedly that would only have reported "invalid argument". Still, that is useful information and might well have led you to the conclusion that the open mode was wrong (as it did for me).

share|improve this answer

You may want to use the truncate command:

truncate --size=1G test.txt

SIZE can be specified as bytes, KB, K, MB, M, etc. I assume you can calculate the desired size by hand; if not, you could probably use the stat command to get information about the file's current size.

share|improve this answer
thanks, wish I could mark both as answers. +1 –  xpt Aug 8 '13 at 18:27
The link is broken. –  Peter Mortensen Aug 26 '13 at 19:34
@PeterMortensen, please try again. The link works for me. It is just the man page for the truncate command, along with a note that it is provided by coreutils_8.20-3ubuntu5_i386 ( –  ChrisInEdmonton Aug 26 '13 at 20:54
Its documentation (in info format) from coreutils. –  Cristian Ciupitu Jun 22 '14 at 15:47

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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