How to replace text while maintaining capitalization?

Let's say I wanted to replace the line in the file with the following contents

name nAmE naMEbb NAME 

And I wanted to replace the word "name" with "dave", but keep a capital copy of the source text. For example, my desired result would be,

 dave dAvE daVEbb DAVE 

Are there any single line lines for this (preferably in Perl, so I can do in-place replacements in many files)?

EDIT The problem is ambiguous if both lines do not have the same length. Suppose this is so.

+8
string regex replace perl
source share
3 answers

There are several 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 the solutions presented there allows one-line substitution by defining a subroutine (preserve_case):

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

Fingerprints: This is a SUcCESS Case

+8
source share

He is crazy, but he works:

 perl -e 'use List::MoreUtils "pairwise"; $_ = "toto naME nAmE"; s/(name)/@x = map(ord, split "", "DAVE"); @y = map(ord>=97?32:0, split "", $1); @c = map chr, pairwise { $a + $b } @x, @y; $" = ""; "@c";/gei; print "$_\n";' 

single line solution!

0
source share

I wonder if the perlfaq example works for non-ASCII. An option that does not use an XOR hack might be:

 $text =~ s{$str_to_replace}{my $i=0;join "",map {substr($&,$i++,1)=~/\p{IsLower}/?lc:uc} split //,$str_to_substitute}ieg; 

But this only works if the /i modifier is included in the locale (see perllocale).

0
source share

All Articles