我工作的一個函數來sed
執行多個key=value
換人:sed的 - 批 '鍵=值' 替代
batch_sub() {
local file="${@: -1}" # Last argument is file to be changed.
[[ -w "${file}" ]] || { echo "Invalid file: ${file}" ; return 1 ; }
for arg in "${@}" ; do
[[ $arg =~ (.*)=(.*) ]] || continue
# 'trim_str' will trim leading & trailing spaces.
local key=$(trim_str "${BASH_REMATCH[1]}")
local value=${BASH_REMATCH[2]}
sed -i '[email protected]'"\(${key}"' *=\).*@\1'"${value}"'@' "${file}"
done
}
這個函數接受類似的參數:
batch_sub "a = x" "b = y" "c = z" "a.b.d.e=udp://b:8080" "/tmp/file"
和工作正常。但我要的是讓它接受的參數是這樣的:
batch_sub "a = x b = y c = z a.b.d.e=udp://b:8080" "/tmp/file"
此外,這將是很好,如果sed
在這個函數中調用一次:
sed -i -e 's/$key=/\1$value/'
-e 's/$key1=/\1$value1/'
'/tmp/file'
請告知。
注意' 'S/$鍵=/\ $ 1值/''不會擴大,因爲單引號的變量。你可以建立在bash的數組(在bash 4的關聯數組),或者你可以使用分號混搭你的sed替代在一起。但是你一定需要一個簡潔的輸入格式。你的功能已經接受的工作正常,但你「想要」的那個不清楚。如果$ value中有等號,該怎麼辦? – ghoti
是的,謝謝你的頭了,我所知道的是,那些只是僞代碼,有點懶的類型和配對所有的'「'。:) 感謝的提示」混搭在一起,你的sed使用分號」替代 而我想我會離開‘如果有在'$ value'等號’現在:) – leafei