我正在嘗試使用 bash 腳本的 sed 功能來查找和替換檔案中的內容。不確定我的方法是否正確,但我不想使用正則運算式。
輸入:
<if property="headless">
<VMArg name="-Djava.awt.headless=true"/>
</if>
<VMArg name="-Dfile.encoding=UTF-8"/>
<VMArg name="-Djava.util.logging.config.file=$VDISTDIR/system/conf/logging.properties"/>
<VMArg name="-Dlog4j.configurationFile=file:///$VDISTDIR/system/conf/log4j2.yaml"/>
預期的:
<if property="headless">
<VMArg name="-Djava.awt.headless=true"/>
</if>
This is the replaced text
<VMArg name="-Dfile.encoding=UTF-8"/>
<VMArg name="-Djava.util.logging.config.file=$VDISTDIR/system/conf/logging.properties"/>
<VMArg name="-Dlog4j.configurationFile=file:///$VDISTDIR/system/conf/log4j2.yaml"/>
試圖開發類似下面的東西,但不幸的是它不起作用。
#!/bin/bash
find='<if property="headless">
<VMArg name="-Djava.awt.headless=true"/>
</if>
<VMArg name="-Dfile.encoding=UTF-8"/>'
replace='<if property="headless">
<VMArg name="-Djava.awt.headless=true"/>
</if>
<VMArg name="-Dfile.encoding=UTF-8"/>'
sed "s/$find/$replace/g" filename.input
錯誤:
sed: -e expression #1, char 7: unterminated `s' command
uj5u.com熱心網友回復:
答案是:
sed -i -e '1h;2,$H;$!d;g' -Ee 's/(<VMArg name="-Djava.awt.headless=true"\/>\n\s <\/if>)/\1\nThis Is replaced text/' file
作業解決方案:
$ cat file
<if property="headless">
<VMArg name="-Djava.awt.headless=true"/>
</if>
<VMArg name="-Dfile.encoding=UTF-8"/>
<VMArg name="-Djava.util.logging.config.file=$VDISTDIR/system/conf/logging.properties"/>
<VMArg name="-Dlog4j.configurationFile=file:///$VDISTDIR/system/conf/log4j2.yaml"/>
$ cat file | sed -e '1h;2,$H;$!d;g' -Ee 's/(<VMArg name="-Djava.awt.headless=true"\/>\n\s <\/if>)/\1\nThis Is replaced text/'
<if property="headless">
<VMArg name="-Djava.awt.headless=true"/>
</if>
This Is replaced text
<VMArg name="-Dfile.encoding=UTF-8"/>
<VMArg name="-Djava.util.logging.config.file=$VDISTDIR/system/conf/logging.properties"/>
<VMArg name="-Dlog4j.configurationFile=file:///$VDISTDIR/system/conf/log4j2.yaml"/>```
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/521556.html
標籤:linux重击
上一篇:將檔案名作為列插入,以逗號分隔
