开发者

How to shave off last character using sed?

开发者 https://www.devze.com 2023-01-15 16:43 出处:网络
That is, going from ABCD ->开发者_StackOverflow社区 ABCYou can try: sed s\'/.$//\' The regex used is .$

That is, going from ABCD ->开发者_StackOverflow社区 ABC


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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消