我一直在嘗試撰寫一個 bash 腳本,該腳本可以在目錄中遞回搜索并用#{DEMO_STRING_1}環境變數(例如$sample1.
完整腳本:
#!/bin/sh
find /my/path/here -type f -name '*.js' -exec sed -i \
-e 's/#{DEMO_STRING_1}/'"$sample1"'/g' \
-e 's/#{DEMO_STRING_2}/'"$sample2"'/g' \
-e 's/#{DEMO_STRING_3}/'"$sample3"'/g' \
-e 's/#{DEMO_STRING_4}/'"$sample4"'/g' \
-e 's/#{DEMO_STRING_5}/'"$sample5"'/g' \
-e 's/#{DEMO_STRING_6}/'"$sample6"'/g' \
-e 's/#{DEMO_STRING_7}/'"$sample7"'/g' \
-e 's/#{DEMO_STRING_8}/'"$sample8"'/g' \
{}
我不知道如何用帶有花括號的主題標簽替換字串。
我試過這個例子:sed 用花括號或環境變數替換在 sed 中查找和替換,但我不知道如何組合它們。
我錯過了什么?我還搜索了需要轉義的字符,例如在 sh 腳本中使用 sed 時需要轉義哪些字符?但又不是我需要的角色。
具體格式拋出以下錯誤:
sed: bad option in substitution expression
我哪里錯了?
更新:環境變數示例:
- https://www.example.com
- /示例字串/
- 12345-abcd-54321-efgh
- base64 字串
以上所有情況都是我要替換的環境變數。所有環境變數都在雙引號內。
uj5u.com熱心網友回復:
重要的是要了解環境變數參考是由 shell 擴展的,因為它準備執行命令,而不是命令本身(sed在這種情況下)。該命令僅查看擴展的結果。
在您的情況下,這意味著如果任何環境變數的值包含sed在背景關系中有意義的字符,例如未轉義的 (to sed) 斜杠 ( /),sed則將賦予它們特殊意義,而不是將它們解釋為普通字符。例如,給定一個sed命令,例如
sed -e "s/X/${var}/" <<EOF
Replacement: X
EOF
, 如果 的值為$var則Y輸出為
Replacement: Y
,但如果$varis /path/to/Ythen的值sed將失敗,并出現您報告的相同錯誤。發生這種情況是因為sed實際運行的命令與您鍵入的命令相同
sed -e s/X//path/to/Y
,其中包含無效s指令。最好的選擇可能是轉義替換字串字符,否則這些字符對sed. 你可以通過插入一個 shell 函式來做到這一點:
escape_replacement() {
# replace all \ characters in the first argument with double backslashes.
# Note that in order to do that here, we need to escape them from the shell
local temp=${1//\\/\\\\}
# Replace all & characters with \&
temp=${temp//&/\\&}
# Replace all / characters with \/, and write the result to standard out.
# Use printf instead of echo to avoid edge cases in which the value to print
# is interpreted to be or start with an option.
printf -- "%s" "${temp//\//\\/}"
}
然后腳本會像這樣使用它:
find /my/path/here -type f -name '*.js' -exec sed -i \
-e 's/#{DEMO_STRING_1}/'"$(escape_replacement "$sample1")"'/g' \
...
請注意,您可能還想使用顯式指定支持替換參考 ( ${parameter/pattern/replacement}) 的 shell 的 shebang 行,因為 POSIX 不需要這些,并且您可能會遇到/bin/sh不支持它們的 shell 的系統。如果您愿意依賴 Bash,那么這應該反映在您的 shebang 行中。或者,您可以準備一個escape_replacement不依賴替換參考的函式版本。
uj5u.com熱心網友回復:
如果你使用perl- 你不需要逃避任何東西。
匯出shell 變數后,您可以通過$ENV{name}perl 內部訪問它。
例子:
samples=(
https://www.example.com
'/sample string/'
12345-abcd-54321-efgh
'base64 string'
$'multi\nline'
)
for sample in "${samples[@]}"
do
echo '---'
export sample
echo 'A B #{DEMO_STRING_1} C' |
perl -pe 's/#{DEMO_STRING_1}/$ENV{sample}/g'
done
echo '---'
輸出:
---
A B https://www.example.com C
---
A B /sample string/ C
---
A B 12345-abcd-54321-efgh C
---
A B base64 string C
---
A B multi
line C
---
要添加-i選項,您可以:perl -pi -e 's///'
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/439465.html
上一篇:自動修復聲納規則
