tags:

views:

65

answers:

4

I want to replace the date found at the end of the "datadir" line with the current date. For e.g. my my.cnf file looks like this...

# head /etc/my.cnf
[mysqld]

#mount -t tmpfs -o size=102m tmpfs /mnt
#datadir=/mnt
read-only
datadir=/mysqlApr5
#datadir=/mysqlApr2
#datadir=/mysqlMar16
#datadir=/mysqlFeb25a

Most of the lines are commented. I need to find the datadir line that is not commented and then replace the /mysqlApr4 with /mysqlApr20

datadir=/mysqlApr20

If it is possible I will like to comment the older datadir path.

#datadir=/mysqlApr5

I can output the current date as:

date '+%b%d'

But I want to concat it with the word "/mysql" and replace or comment the current datadir line.

+2  A: 

You can do it with sed and an in-place replacement:

sed -i "s|^datadir=.*$|datadir=/mysql`date '+%b%d'`|" /etc/my.cnf

If you want to comment out the old line and add a new one, you can use sed to do the commenting and just append a new line:

sed -i "s|^datadir=.*$|#\\0|" /etc/my.cnf
echo "datadir=/mysql`date '+%b%d'`" >> /etc/my.cnf
Michael Mrozek
A: 

Perl one-liner which edits the file in-place:

perl -i -nle 'BEGIN { $date = `date +%b%d` }; if (/^datadir=/) { print qq{#$_\ndatadir=/mysql$date} } else {print}' my.cnf
Alan Haggai Alavi
A: 
awk -vd="$(date +%b%d)" '!/#/&&/datadir/{$0="#"$0"\ndatadir=/mysql"d}1' /etc/my.cnf>temp && mv temp file
ghostdog74
A: 

All in one fell swoop:

sed -i '/^datadir.*/{s.^.#.;s.$.\ndatadir=/mysql'$(date "+%b%d")'.;q}' /etc/my.cnf

This will comment out the uncommented line. It adds the new line immediately below the old one instead of at the end of the file so it works similarly to the AWK and Perl versions shown.

Dennis Williamson