Uppercase last n characters of every line in a wordlist regexp

115 views Asked by At

I'm looking for a way to uppercase the last n characters of every line in a wordlist, using regular expression. Example with n=3:

Input:

thisisatest
uppercasethelast3characters

Desired output:

thisisatEST
uppercasethelast3charactERS
3

There are 3 answers

1
sat On BEST ANSWER

Use this GNU sed:

sed -e 's/^\(.*\)\(.\{3\}\)$/\1\U\2/' file

With extended regex:

sed -r 's/^(.*)(.{3})$/\1\U\2/' file

Test:

$ sed -e 's/^\(.*\)\(.\{3\}\)$/\1\U\2/' file
thisisatEST
uppercasethelast3charactERS
2
Casimir et Hippolyte On

Without the \U feature (that is a GNU feature), it's a bit less handy:

sed -e 'h;s/.\{3\}$//;x;s/.*\(.\{3\}\)/\1/;y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/;H;g;s/\n//;' file

details:

h              # copy the pattern space into the buffer space
s/.\{3\}$//    # remove the 3 last characters (in the pattern space)
x              # exchange the pattern space and the buffer space
s/.*\(.\{3\}\)/\1/ # remove all characters except the three last
# translate lower case to upper case letters 
y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/
H  # append the pattern space to the buffer space
g  # replace the pattern space with the buffer space
s/\n// # remove the newline character
0
elcaro On

Since you tagged perl, I'm posting a perl solution...

# with RegEx
perl -nle '/(.*)(.{3})$/; print $1 . uc $2;' file.txt
# formatted with n at the end
cat file.txt | perl -nle 'print $1 . uc $2 if /(.*)(.{3})$/;'

# or without RegEx
perl -nle '$n=3; print substr($_,0,-$n).uc substr($_,length($_)-$n);' file.txt
# formated with n at the end
cat file.txt| perl -nle 'print substr($_,0,-$n).uc substr($_,length($_)-$n) if $n=3;'

The substr solution will be a lot faster than doing regex captures.