这可能很疯狂。但是使用您设置的要求可能是这样的:)
#!/bin/bash
declare -r self=${0##*\/}
# Left and right trim
trim_str()
{
local tmp="${1##[[:space:]]}"
printf "%s" "${tmp%%[[:space:]]}"
}
# Replace \ with \\, / with \/, & with \&
sed_esc_repl()
{
local tmp="${1//\\/\\\\}"
tmp="${tmp//\//\\/}"
tmp="${tmp//&/\&}"
printf "%s" "$tmp"
}
# Additional escape on search pattern
# escape *.][|
sed_esc_key()
{
local tmp=$(sed_esc_repl "$1")
tmp="${tmp//./\.}"
tmp="${tmp//\*/\*}"
tmp="${tmp//|/\|}"
tmp="${tmp//[/\[}"
tmp="${tmp//]/\]}"
printf "%s" "$tmp"
}
batch_sub()
{
local file=""
local -a argv
local key=
local val=
local sedstr=""
local old_ifs=$IFS
if (( $# < 2 )); then
printf "Usage: $self \"replacement pairs\" <file>\n"
return 1
elif (( $# > 2 )); then
file="${@: -1}"
argv=( "${@:1:$(($#-1))}" ) # Everything but last arg
else
file="$2"
argv=( "$1" )
fi
[[ -w "${file}" ]] || { printf "Invalid file: %s\n" "${file}"; return 1; }
# Set IFS to match space and equal sign.
IFS='='' '
for arg in ${argv[@]}; do
if [[ "$key" != "" ]]; then
sedstr+="s/\("$(sed_esc_key "$key")"\) *=.*/\1="$(sed_esc_repl "$arg")"/g;"
key=
else
key="$arg"
fi
done
IFS="$old_ifs"
printf "sed string:\"%s\"\n\n" "${sedstr%%;}"
sed -i "${sedstr%%;}" "$file"
}
# Create example / test file:
printf "\
x[a-zA-Z].*? = mixture1
x[a-zA-Z].*p? = mixture2
x = foo
b*x = fafa
a\\\\1c = moo
a.b$.d.e=zim zala bim
" > tst
batch_sub "$@"
exit $?
通过即运行:
./keysw "x[a-zA-Z].*p? = xb*x = ya\1c = \z\n\1 ab$.de=udp&://b:\8080" tst && cat tst
或者
./keysw "x[a-zA-Z].*p? = x" \
"b*x = y" \
"a\1c = \z\n\1" \
"a.b$.d.e=udp&://b:\8080" \
tst && cat tst
给予;
文件:
x[a-zA-Z].*? = mixture1
x[a-zA-Z].*p? = mixture2
x = foo
b*x = fafa
a\1c = moo
a.b$.d.e=zim zala bim
结果:
x[a-zA-Z].*? = mixture1
x[a-zA-Z].*p?=x
x = foo
b*x=y
a\1c=\z\n\1
a.b$.d.e=udp&://b:\8080