我希望這對某人來說是一件容易的事(唉,不是我!)。
使用 bash 腳本,我想替換組態檔“/etc/app/app.cfg”(ini 樣式)中的值,使用變數進行搜索和替換。
我希望更新的值名稱和值(注意等號兩邊的空格:
LOGDIR = /etc/app/logs
我在 bash 腳本中定義了以下內容:
# Get existing LogDir value
CURRENT_LOGDIR=$(grep 'LogDir =' /pathtofile | sed 's/LogDir *= *//g')
# Set New LogDir
LOGDIR=/mnt/eft/fs1/logs
# Update LogDir if different
if [[ -d $(echo $CURRENT_LOGDIR) != $LOGDIR ]] ; then
# Update LogDir value:
**bash command - I need help with !**
fi
我嘗試了許多與 sed 的組合,但無濟于事,因此提出了這個問題。
我嘗試過的事情:
echo "LogDir = $LOGDIR" | sed '#s/$CURRENT_DIR/$LOGDIR/#g' /etc/app/app.cfg
sed -i '/#/!s/\(LogDir[[:space:]]*=[[:space:]]*\)\(.*\)/\1$LOGDIR#/g' /etc/app/app.cfg
sed -i 's/LogDir[[:space:]]=.*/LogDir = {LOGDIR}/' /etc/app/app.cfg
sed -i "s/^LogDir[[:space:]]*=.*/LogDir=$LOGDIR/}" /etc/app/app.cfg
sed -i '/#/!s/\(LogDir[[:space:]]*=[[:space:]]*\)\(.*\)/\1"$LOGDIR"/' /etc/app/app.cfg
期望的輸出:
更新 /etc/app/app.cfg 中的 LogDir 值
例如:
LogDir = /mnt/eft/fs1/logs
uj5u.com熱心網友回復:
那}最后在做什么?看起來像一個錯字。
sed "s/^LogDir[[:space:]]*=.*/LogDir=$LOGDIR/" /etc/app/app.cfg
和sed 編輯檔案到位
uj5u.com熱心網友回復:
使用sed
$ LOGDIR=/mnt/eft/fs1/logs
$ sed -i.bak "s|\([^=]*=[[:space:]]\).*|\1$LOGDIR|" /etc/app/app.cfg
$ cat /etc/app/app.cfg
LOGDIR = /mnt/eft/fs1/logs
uj5u.com熱心網友回復:
這個怎么樣:
awk '$1 == "LogDir" {print "LogDir = /mnt/eft/fs1/logs"; next} {print}' old_configuration_file >new_configuration_file
第一個 awk 子句用新的 LogDir 條目替換舊的LogDir條目,第二個子句通過其他行保持不變。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/439467.html
下一篇:如何在后臺運行命令并捕獲輸出
