shantanuo
shantanuo

Reputation: 32276

replace a text string

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.

Upvotes: 1

Views: 915

Answers (4)

Dennis Williamson
Dennis Williamson

Reputation: 360685

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.

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 343077

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

Upvotes: 0

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74272

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

Upvotes: 0

Michael Mrozek
Michael Mrozek

Reputation: 175705

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

Upvotes: 4

Related Questions