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
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
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.
Use this GNU
sed
:With extended regex:
Test: