Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shrink (truncate) file from beginning on linux

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().

like image 227
woky Avatar asked Feb 23 '11 22:02

woky


People also ask

How do I truncate a file in Linux?

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 .

How do I remove the first N line from a file?

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.


1 Answers

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

like image 183
Francesquini Avatar answered Oct 25 '22 07:10

Francesquini