Search code examples
awkcronscheduled-tasksselectionorg-mode

How to systematically replace certain parts of a file?


I am using orgmode on Emacs and want to automatically update parts of an orgmode file using cron scheduling.

I know how to get the cron job to run at the times I choose but now I am faced with the issue of selecting certain parts of the file to change.

I would like to increment numbers at a certain locations in a file everyday (like every day at 3am or something).

So say I have the file fruit.org:

* Apple
age: 2
* Bananas 
age: 1
A really bad fruit
* Cranberry
* Death
* Easter
A cool day

I want to select all the numerical values after age and then increment them every day. How would I do this selection and replacing. I believe it would involve regexp and some tool (maybe awk) but I am relatively clueless from there on.


Solution

  • In awk, you could say:

    awk '/age:/ { $2++ } { print }' foo.org
    

    If you have a recent version of GNU awk, you can edit the file in-place using the option -i inplace. Otherwise, just do the usual, i.e. redirect to a temporary file and then replace the original:

    awk '/age:/ { $2++ } { print }' foo.org > foo.org.tmp && mv foo.org{.tmp,}
    

    That's basically what the inplace option of awk or sed does behind the scenes anyway.