標題中的名字說明了一切。但是,我絕對是 sed 命令最差的。所以我正在嘗試編輯以下檔案:
/var/www/html/phpMyAdmin/config.inc.php
我想編輯說
//some text here
$cfg['Servers'][$i]['AllowRoot'] = false;<br />
//some more text here
Run code snippetHide resultsExpand snippet
進入以下
//some text here
$cfg['Servers'][$i]['AllowRoot'] = true;<br />
//some more text here
Run code snippetHide resultsExpand snippet
它有很多特殊字符等等,我對 sed 的作業原理一無所知。所以這里有一些我試圖專門編輯這一行的命令。
sed -i "/*.AllowRoot.*/\$cfg['Servers'][\$i]['AllowRoot'] = true;/" /var/www/html/phpMyAdmin/config.inc.php
sed -i "/*.AllowRoot.*/$cfg['Servers'][$i]['AllowRoot'] = true;/" /var/www/html/phpMyAdmin/config.inc.php
<!-- The below finds the line succesfully and prints it so I know it's got the right string -->
sed -n '/AllowRoot/p' /var/www/html/phpMyAdmin/config.inc.php
<!-- End of that line lol -->
sed -i "s/'AllowRoot|false'/'AllowRoot|true'/" /var/www/html/phpMyAdmin/config.inc.php
Run code snippetHide resultsExpand snippet
我完全不知道我在做什么,除了最后一個命令拆分'AllowRoot | false'的感覺之外,我并沒有學到很多東西,以確保這兩個命令都必須出現在句子中才能回傳。所以按照我的邏輯,我認為將“假”這個詞改為“真”會實作這一點,但什么也沒有。其他命令回傳......充其量是奇怪的結果,甚至清空檔案。或者那是我沒有在這里寫下的命令之一,我在嘗試了 50 次后就迷失了方向。這里的解決方案是什么?
親切的問候,
帕特里克
uj5u.com熱心網友回復:
[and]需要轉義以匹配文字括號,而不是無意中開始括號運算式。這應該有效:
$ sed -i "/\$cfg\['Servers'\]\[\$i\]\['AllowRoot'\]/s/false/true/" /var/www/html/phpMyAdmin/config.inc.php
uj5u.com熱心網友回復:
在 sed 中沒有多少東西可以逃避。您行中的主要問題是/您選擇了哪個分隔符(最常見,但不是必需的)。我建議您使用#以下方法:
sed -i "s#$cfg['Servers'][$i]['AllowRoot'] = false;<br />#$cfg['Servers'][$i]['AllowRoot'] = true;<br />#g" input.txt
但是,您還需要考慮 bash 解釋器。$i 和 $cfg 將被解釋為變數。我的建議是,當您想匹配這樣的字串時,將 sed 運算式放在這樣的文本檔案中:
cat allow_root_true.sed
s#['Servers'][]['AllowRoot'] = false;<br />#['Servers'][]['AllowRoot'] = true;<br />#g
并像這樣運行命令sed -f:
sed -i -f allow_root_true.sed input.txt
警告-i將更改輸入檔案
uj5u.com熱心網友回復:
sed 無法進行文字字串匹配,這就是為什么您需要轉義這么多字符的原因(請參閱Is it possible to escape regex metacharacters reliable with sed),但 awk 可以:
$ awk -v str="\$cfg['Servers'][\$i]['AllowRoot']" 'index($0,str){sub(/false/,"true")} 1' file
//some text here
$cfg['Servers'][$i]['AllowRoot'] = true;<br />
//some more text here
Run code snippetHide resultsExpand snippet
在上面我們只需要對$s 進行轉義以保護它們免受 shell 的影響,因為字串包含在"s 中以允許它包含's。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/493700.html
上一篇:Gnuplot:每分鐘頻率
