3

I need to periodically empty a text file without deleting it (I know how many lines it has).

I tried this:

Created a cron that executes the following script

other lines from the script here

sed '1,14d' file.txt>file.txt

If I run it from a terminal it works fine, but when I run the cron it executes the first part (the "other lines from script here" part) but it doesn't empty the file.

Note: The file has 777 permissions so I don't think it's permissions related.

  • 1
    I'm surprised you say that sed 1,14d file > file works: the shell will see the redirection and truncate the file before executing the sed command. – glenn jackman Mar 30 '11 at 17:43
4

Maybe the current working directory isn't what you're expecting when cron executes the script. Try specifying the full path to file.txt. Also, this should empty the file as well, just in case there's some issue with the sed command:

echo > file.txt
  • Specified the full path and replaced sed with echo and now it works fine. Thank you – zozo Mar 30 '11 at 11:34
  • Cool, glad it was a simple fix. – db2 Mar 30 '11 at 12:15
  • 5
    Just thought I'd mention that even though this may fix your problem, it does not empty the file, but rather leaves a newline char in the file. – beans Mar 30 '11 at 14:40
10

You can try a simple >file.txt

$ cat file.txt
this is a test
$ >file.txt
$cat file.txt
$
  • 2
    This is the most relevant one as it dose empty the file. – Fish Monitor Mar 30 '11 at 15:12
4

You can also use logrotate, which gives you the option of not just emptying the file, but archiving (e.g., compressing) the previous contents of the file, and even mail the file to you.

2

The traditional un*x way to "empty" a file:

$ cat /dev/null > myfile

Moving the file & touching a new file (hence, changing the file descriptor) may prevent existing apps from continuing to write to the file, so that generally is undesirable. If a copy if the existing file is required, you can do something like (although, note it's not atomic, so some date may be duplicated in both files):

$ cp myfile myfile-$(date '+%F') && cat /dev/null > myfile

And, as mentioned, 'cron' jobs do not usually run in the directory you expect; but you can "cd" to your desired directory in the script to do the work & still use relative paths.

1

I would do this: mv file file.bak && touch file && rm file.bak

I move the file first, in case the system happens to have it open.

1

You can even use truncate(1), if your system has it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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