Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Replace Text while Maintaining Capitalization?

Say I wanted to a string replace on a file with the following contents

name
nAmE
naMEbb
NAME

And wanted to replace the word "name" with "dave", but keeping the capitalization of the original text. For example, my desired output would be,

dave
dAvE
daVEbb
DAVE

Are there any one-liners to do this (preferably in Perl so I can do an in-place substitution across many files)?

EDIT The problem is ambiguous unless both strings have exactly the same length. Let's assume it does.

like image 819
duckworthd Avatar asked Aug 09 '11 20:08

duckworthd


People also ask

How do you capitalize text without retyping?

DID YOU ACCIDENTALLY TYPE A WHOLE PARAGRAPH IN ALL CAPS? No need to retype it, says our friends at LawTech Partners! Simply use Word's “change case” feature to quickly convert text from ALL CAPS to Sentence Case or other. Look for the “Change Case” button on the Ribbon or use keyboard shortcuts after selecting text.

How do you replace words without caps in Word?

If you want to use the Small Caps or All Caps options to change visible case, click in the Replace field, choose Format | Font then apply the font settings you want. In this case 'Small caps'. Use the same method to enforce any other formatting.

How do I make Find and Replace case sensitive?

By default, the search process is case insensitive. If you want to make it case sensitive, just check the Match case box in the Find dialog.


1 Answers

There are some solutions on perlFaq: http://perldoc.perl.org/perlfaq6.html#How-do-I-substitute-case-insensitively-on-the-LHS-while-preserving-case-on-the-RHS?

One of solutions presented there allows to perform the substitution in a single line, by defining a subroutine (preserve_case):

   $string = "this is a TEsT case";
   $string =~ s/(test)/preserve_case($1, "success")/egi;
   print "$string\n";

This prints: this is a SUcCESS case

like image 147
mMontu Avatar answered Oct 18 '22 18:10

mMontu