大写单词列表正则表达式中每行的最后 n 个字符
Uppercase last n characters of every line in a wordlist regexp
我正在寻找一种使用正则表达式将单词列表中每一行的最后 n 个字符大写的方法。 n=3 的示例:
输入:
thisisatest
uppercasethelast3characters
期望的输出:
thisisatEST
uppercasethelast3charactERS
使用这个 GNU sed
:
sed -e 's/^\(.*\)\(.\{3\}\)$/\U/' file
使用扩展正则表达式:
sed -r 's/^(.*)(.{3})$/\U/' file
测试:
$ sed -e 's/^\(.*\)\(.\{3\}\)$/\U/' file
thisisatEST
uppercasethelast3charactERS
没有 \U
功能(这是 GNU 功能),它不太方便:
sed -e 'h;s/.\{3\}$//;x;s/.*\(.\{3\}\)//;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\}\)// # 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 . uc ;' file.txt
# formatted with n at the end
cat file.txt | perl -nle 'print . uc 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
解决方案比正则表达式捕获快 很多。
我正在寻找一种使用正则表达式将单词列表中每一行的最后 n 个字符大写的方法。 n=3 的示例:
输入:
thisisatest
uppercasethelast3characters
期望的输出:
thisisatEST
uppercasethelast3charactERS
使用这个 GNU sed
:
sed -e 's/^\(.*\)\(.\{3\}\)$/\U/' file
使用扩展正则表达式:
sed -r 's/^(.*)(.{3})$/\U/' file
测试:
$ sed -e 's/^\(.*\)\(.\{3\}\)$/\U/' file
thisisatEST
uppercasethelast3charactERS
没有 \U
功能(这是 GNU 功能),它不太方便:
sed -e 'h;s/.\{3\}$//;x;s/.*\(.\{3\}\)//;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\}\)// # 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 . uc ;' file.txt
# formatted with n at the end
cat file.txt | perl -nle 'print . uc 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
解决方案比正则表达式捕获快 很多。