![](/img/trans.png)
[英]bash - replacing multiple lines in a file with a single line from another file
[英]Trouble replacing a single line in a file with multiple lines (BASH)
這是設置,我有兩個變量:
$ echo "${ORIGINALSTRING}"
placeholdertext
$ echo "${REPLACEMENTSTRING}"
-----BEGIN CERTIFICATE-----
thisisarandombase64encodedstring
blahblahblahblahblahblahblahblah
blahblahblahblahblahblahblahblah
blahblahblahblahblahblahblahblah
blahblahblahblahblahblahblahblah
-----END CERTIFICATE-----
我需要用包含多行的字符串替換文本文件中存在的原始字符串。 我用sed
陷入了死胡同:
$ sed -i "s/${ORIGINALSTRING}/${REPLACEMENTSTRING}/g" ./somedir/file.txt
sed: -e expression #1, char 48: unterminated `s' command
我在同一個命令上嘗試了大約兩打變體,但最終我發現它是由具有多行的環境變量之一引起的。 所以,遺憾的是sed
已經過時了。
有沒有人對如何完成這項任務有任何其他想法? 我聽說也許awk
可以做我想做的事,但我還沒有看到任何與我的特定用例相關的好例子。
ORIGINALSTRING="$ORIGINALSTRING" REPLACEMENTSTRING="$REPLACEMENTSTRING" awk '
BEGIN {
old = ENVIRON["ORIGINALSTRING"]
new = ENVIRON["REPLACEMENTSTRING"]
}
s = index($0,old) {
$0 = substr($0,1,s-1) new substr($0,s+length(old))
}
{ print }
' file
無論哪個 shell 變量中有什么字符,上述內容都將起作用,因為它使用文字字符串進行搜索和替換,而如果/
、 &
、 \\1
、 .
、 *
、 ^
、 $
或其他各種字符出現在其中一個或另一個中,因為 sed 沒有使用文字字符串的功能,請參閱是否可以使用 sed 可靠地轉義正則表達式元字符。
我幾乎總是建議使用ed
來編輯它的文件,而不是嘗試使用非標准的sed -i
:
printf "%s\n" "g/$ORIGINALSTRING/c" "$REPLACEMENTSTRING" . w | ed -s input.txt
這個C hanges每一行匹配ORIGINALSTRING
到線REPLACEMENTSTRING
(的.
手段結束輸入了所謂的插入模式)和W儀式更改的文件恢復到磁盤。
sed
的等效項需要在每一行的末尾添加一個\\\\
以插入但最后一個:
sed -i "/$originalstring/c\\
${replacementstring//$'\n'/\\$'\n'}" input.txt
另請參閱更正 bash 和 shell 腳本變量大寫,並考慮是否應該使用所有大寫變量名。
用 sed 和 bash 及其參數擴展用多行字符串替換字符串:
ORIGINALSTRING='placeholdertext'
REPLACEMENTSTRING='-----BEGIN CERTIFICATE-----
thisisarandombase64encodedstring
blahblahblahblahblahblahblahblah
blahblahblahblahblahblahblahblah
blahblahblahblahblahblahblahblah
blahblahblahblahblahblahblahblah
-----END CERTIFICATE-----'
sed -i "s|${ORIGINALSTRING}|${REPLACEMENTSTRING//$'\n'/\\n}|" file
我從s///
切換到s|||
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.