I have a source code spread across several files.
- It has a pattern
abcdef
which I need to replace withpqrstuvxyz
. - The pattern could be
Abcdef
(Sentence Case) then it needs to be replaced withPqrstuvxyz
. - The pattern could be
AbCdEf
(Toggle case) then it needs to be replaced withPqRsTuVxYz
.
In short, I need to match the case of the source pattern and apply the appropriate destination pattern.
How can I achieve this using sed
or any other tool?
Best Answer
Portable solution using
sed
:It's a bit easier with GNU sed:
By using
&&&
above, we reuse the case pattern of the string for the rest of the replacement, SoABcdef
would be changed toPQrstuVWx
andAbCdEf
toPqRsTuVwX
. Change it to&
to affect only the case of the first 6 characters.(note that it may not do what you want or may run into an infinite loop if the replacement may be subject to substitution (for instance if substituting
foo
forfoo
, orbcd
forabcd
)