大写最后一个字列表regexp中每行的n个字符

时间:2016-02-12 12:12:26

标签: regex perl awk sed word-list

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

输入:

thisisatest
uppercasethelast3characters

期望的输出:

thisisatEST
uppercasethelast3charactERS

3 个答案:

答案 0 :(得分:3)

使用此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

答案 1 :(得分:2)

由于您标记了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 :(得分:0)

如果没有\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