How do I search/and replace like this using sed or another tool

 Foo => Bar
 foo => bar

That is: Look for foo regardless of case, and replace with the same case pattern.

One "solution" is to run sed once for each case-sensitive pattern but it becomes more work.

  • Please edit your question to include information like the program and/or OS you're talking about. also include what you've tried already and what the results were. – Ƭᴇcʜιᴇ007 Jul 22 '14 at 17:02
  • 1
    @Ƭᴇcʜιᴇ007 Hope my edit is enough. I accept solutions for Linux or Windows – user877329 Jul 22 '14 at 17:12
  • This is straight forward sed -i -r -e 's/FOO/BAR/g' -e 's/Foo/Bar/g' -e 's/foo/bar/g' file – clement Jul 23 '14 at 13:59
  • similar question – eadmaster Dec 19 '15 at 10:30

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
    echo -n "${R:$I:1}" # print single letter unaltered without linefeed



Same code, more compact:

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
  • Ok so sed or other tools cannot do that... – user877329 Aug 2 '14 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.