cutting last n character in a string using shell script

隐身守侯 提交于 2019-11-30 11:43:31

To answer the title of you question with specifies cutting last n character in a string, you can use the substring extraction feature in Bash.

me@home$ A="123456"
me@home$ echo ${A:0:-2}  # remove last 2 chars
1234

However, based on your examples you appear to want to remove all trailing commas, in which case you could use sed 's/,*$//'.

me@home$ echo "ssl01:49188,ssl999999:49188,,,,," | sed 's/,*$//'
ssl01:49188,ssl999999:49188

or, for a purely Bash solution, you could use substring removal:

me@home$ X="ssl01:49188,ssl999999:49188,,,,,"
me@home$ shopt -s extglob
me@home$ echo ${X%%+(,)}
ssl01:49188,ssl999999:49188

I would use the sed approach if the transformation needs to be applied to a whole file, and the bash substring removal approach if the target string is already in a bash variable.

With sed:

sed 's/,\+$//' file

Using sed:

sed 's/,,*$//g' file 

I guess you need to remove those unnecessary ,'s

sed 's/,,//g;s/\,$//g' your_file

tested:

> cat temp
ssl01:49188,,,
ssl01:49188,
ssl01:49188,,,,,
ssl01:49188,,,
ssl01:49188,
ssl01:49188,,,,,
ssl01:49188,ssl999999:49188,,,,,
ssl01:49188,abcf999:49188,,,,,
> sed 's/,,//g;s/\,$//g' temp
ssl01:49188
ssl01:49188
ssl01:49188
ssl01:49188
ssl01:49188
ssl01:49188
ssl01:49188,ssl999999:49188
ssl01:49188,abcf999:49188
> 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!