替换文本字符串
问题描述:
我想用当前日期替换在“datadir”行末尾找到的日期。 例如我的my.cnf文件看起来像这样...替换文本字符串
# 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
大多数行都是注释。我需要找到一个没有被注释掉datadir的线,然后用/ mysqlApr20
datadir=/mysqlApr20
更换/ mysqlApr4如果有可能,我会想发表评论旧DATADIR路径。
#datadir=/mysqlApr5
我可以输出当前日期为:
date '+%b%d'
但我想用字“/ MySQL的”到Concat的它,并更换或评论当前的datadir线。
sed -i "s|^datadir=.*$|datadir=/mysql`date '+%b%d'`|" /etc/my.cnf
如果你想注释掉旧线,并添加一个新的,你可以用sed做评论,只是追加:
答
你可以用sed和就地更换做新行:
sed -i "s|^datadir=.*$|#\\0|" /etc/my.cnf
echo "datadir=/mysql`date '+%b%d'`" >> /etc/my.cnf
答
Perl的一个班轮其编辑就地文件:
perl -i -nle 'BEGIN { $date = `date +%b%d` }; if (/^datadir=/) { print qq{#$_\ndatadir=/mysql$date} } else {print}' my.cnf
答
awk -vd="$(date +%b%d)" '!/#/&&/datadir/{$0="#"$0"\ndatadir=/mysql"d}1' /etc/my.cnf>temp && mv temp file
答
所有一举:
sed -i '/^datadir.*/{s.^.#.;s.$.\ndatadir=/mysql'$(date "+%b%d")'.;q}' /etc/my.cnf
这将注释掉注释掉线。它将新行紧接在旧文件的下面,而不是在文件末尾,因此它与AWK和Perl版本类似。