1

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.

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0
awk -vd="$(date +%b%d)" '!/#/&&/datadir/{$0="#"$0"\ndatadir=/mysql"d}1' /etc/my.cnf>temp && mv temp file

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.