使用 sed 查找并替换并保留大小写

问题描述 投票:0回答:1

我想搜索和替换字符串,但使用 sed 保持大小写完整

例如,如果我想用

foo
替换所有出现的
bar
,它应该像这样工作:

foo --> bar
FoO --> BaR
fOO --> bAR
FOO --> BAR
bash unix awk sed
1个回答
0
投票

这是一个奇怪的请求,我的解决方案仅适用于相同长度的字符串 - 因为否则,没有信息来定义输出的情况。

#!/bin/bash
#input/output strings
input=tomfoolery
d=fOo;
e=bar;
# turn replacement strings into character-arrays
D=($(echo $d |grep -o .))
E=($(echo $e |grep -o .))
# define output as empty
o=""
# permutate over the individual characters of 'd' and set the case of the corresponding character in 'e'
for i in $(seq 0 $((${#D[@]}-1)) );do
  printf "${D[i]} --> "; # for debugging only
  if [[ $(echo ${D[i]} |grep -c '[A-Z]') -eq 1 ]]; then
    echo ${E[i]} |tr '[a-z]' '[A-Z]'; # for debugging only
    o=${o}$(echo ${E[i]} |tr '[a-z]' '[A-Z]');
  else
    echo ${E[i]}; # for debugging only
    o=${o}${E[i]};
  fi;
done
echo "$o" # for debugging only
echo $input |sed "s@$d@$o@i"
© www.soinside.com 2019 - 2024. All rights reserved.