Is it possible in Linux (and/or on other Unix) 'shrink' file from beginning? I'd like to use it for persistent queue (no existing implementation suits my needs). From end of file I guess it's possible with truncate().
To empty the file completely, use -s 0 in your command. Add a plus or minus sign in front of the number to increase or decrease the file by the given amount. If you don't have proper permissions on the file you're trying to truncate, you can usually just preface the command with sudo .
Using the tac and the sed Commands However, if we can reverse the order of lines in the input file, the problem will turn into “remove first n lines from a file.” A straightforward sed one-liner sed '1,n d' can remove the top n lines. After that, if we reverse the lines again, our problem gets solved.
If you are using ext4, xfs or some other modern file system, since Linux Kernel 3.15 you can use:
#include <fcntl.h>
int fallocate(int fd, int mode, off_t offset, off_t len);
with the FALLOC_FL_COLLAPSE_RANGE
flag.
http://manpages.ubuntu.com/manpages/disco/en/man2/fallocate.2.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With