如何使用 sed 或其他工具进行这样的搜索和替换
FOO => BAR
Foo => Bar
foo => bar
即:无论大小写,查找 foo,并用相同的大小写模式替换。
一个“解决方案”是对每个区分大小写的模式运行一次 sed,但这会增加工作量。
答案1
#!/bin/bash
S="NewYorkCity" # search string
R="minneapolis" # replace template (in lowercase)
declare -u T # -u: automatic convert content to upper case
for ((I=0; I<${#S}; I++)); do # loop over each single letter of $S
if [[ "${S:$I:1}" =~ [A-Z] ]]; then # upper case?
T="${R:$I:1}" # copy single letter to $T (convert to upper case)
echo -n "$T" # print single upper case letter without linefeed
else
echo -n "${R:$I:1}" # print single letter unaltered without linefeed
fi
done
输出:
明尼阿波利斯
相同的代码,更紧凑:
A="NewYorkCity" # search
B="minneapolis" # replace (must be in lowercase)
declare -u X
for ((I=0; I<${#A}; I++)); do if [[ "${A:$I:1}" =~ [A-Z] ]]; then X="${B:$I:1}"; echo -n "$X"; else echo -n "${B:$I:1}"; fi; done