wordlist regexp中每行的最后n个大写字符

wordlist regexp中每行的最后n个大写字符,regex,perl,awk,sed,word-list,Regex,Perl,Awk,Sed,Word List,我正在寻找一种使用正则表达式将单词列表中每行的最后n个字符大写的方法。n=3的示例: 输入: thisisatest uppercasethelast3characters 期望输出: thisisatEST uppercasethelast3charactERS 使用此GNUsed: sed -e 's/^\(.*\)\(.\{3\}\)$/\1\U\2/' file 使用扩展正则表达式: sed -r 's/^(.*)(.{3})$/\1\U\2/' file 测试: $ sed -

我正在寻找一种使用正则表达式将单词列表中每行的最后n个字符大写的方法。n=3的示例:

输入:

thisisatest
uppercasethelast3characters
期望输出:

thisisatEST
uppercasethelast3charactERS

使用此GNU
sed

sed -e 's/^\(.*\)\(.\{3\}\)$/\1\U\2/' file
使用扩展正则表达式:

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

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

如果没有
\U
功能(这是一个GNU功能),它就没有那么方便了:

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

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

因为您标记了perl,所以我发布了一个perl解决方案

# 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;'

substr
解决方案将比执行正则表达式捕获快得多

如果这行只包含2个字符,那么预期的输出会是什么?@crendaline75-我现在删除了我的答案,因为我不想让你改变,但我只是很好奇:是什么让你选择了
sed-e的s/^(.*)\(.\{3\})$/\1\U\2/'文件
,而不是功能上等价但更简洁的
sed's/\{3\}$/\U&/'文件
我发布过?一个更简单的解决方案可能是:
sed'/.\{3\}$/!Bs/\n&/;Hy/abcdefghijklmnopqrstuvwxyz/abcdefghijklmnopqrstuvwxyz/;HGs/\n.*\n/'file
@potong:这个解决方案也可以,但我看不出有什么比它更简单。