How to shave off last character using sed?

六眼飞鱼酱① 提交于 2021-02-06 14:49:23

问题


That is, going from ABCD -> ABC


回答1:


You can try:

sed s'/.$//'

The regex used is .$

  • . is a regex meta char to match anything (except newline)
  • $ is the end of line anchor.

By using the $ we force the . to match the last char

This will remove the last char, be it anything:

$ echo ABCD | sed s'/.$//'
ABC
$ echo ABCD1 | sed s'/.$//'
ABCD

But if you want to remove the last char, only if its an alphabet, you can do:

$ echo ABCD | sed s'/[a-zA-Z]$//'
ABC
$ echo ABCD1 | sed s'/[a-zA-Z]$//'
ABCD1



回答2:


you don't have call external commands if you are using a shell, eg bash/ksh

s="ABCD"
echo ${s/%?/}


来源:https://stackoverflow.com/questions/3675169/how-to-shave-off-last-character-using-sed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!