Showing posts with label bash. Show all posts
Showing posts with label bash. Show all posts

Tuesday, September 11, 2012

Extract filaname from path with regex

Extracting filname from the full path when the path is OPTIONAL is not so easy as it looks at first look.
I would like to extract cc.cc from
/aa/bb/cc.cc 
either from
cc.cc
as well.

Solution:

$ echo "/aa/bb/cc.cc" | perl -pe "s|(?:.*/)?([^/]*)|\1|"
cc.cc
$ echo "/aa/cc.cc" | perl -pe "s|(?:.*/)?([^/]*)|\1|"
cc.cc
$ echo "cc.cc" | perl -pe "s|(?:.*/)?([^/]*)|\1|"
cc.cc

Some explanation: 
  • ?: start non capturing group
  • [^/] any character except slash

Sunday, July 22, 2012

Edit crontab from shell script

Editing crontabs from shell script is not so easy as it sounds first.
You can't simply edit /var/spool/cron/crontabs/user file because you have to install new crontab by running crontab command.

So the right method is:
1. list the current crontabs to a temporary file:
$ crontab -l > crontab.lst


2. Edit/append the created file
$ echo "*/10 * * * * /path/to/new/job" >>crontab.lst

3. Install edited crontab file:
$ crontab crontab.lst