问题描述
如何使用shell脚本从一个特定的字符串删除所有n个字符,
SSL01:49188 ,,,
SSL01:49188,
SSL01:49188 ,,,,,
SSL01:49188,ssl999999:49188 ,,,,,
SSL01:49188,abcf999:49188 ,,,,,
输出将采用以下格式
SSL01:49188
SSL01:49188
SSL01:49188
SSL01:49188,ssl999999:49188
SSL01:49188,abcf999:49188
要回答这个标题你指定质疑切割最后n个字符的字符串上,您可以使用猛砸子提取特征
我@ home的$ A =123456
我@ home的$回声$ {A:0:-2}#删除最后2字符
1234
然而,根据你的例子,你似乎要删除所有尾随逗号,在这种情况下,你可以使用 SED的/,* $ //'
。
我@ home的$回声SSL01:49188,ssl999999:49188 ,,,,,| SED的/,* $ //'
SSL01:49188,ssl999999:49188
,或对于一个纯粹的Bash的解决方案,你可以使用子去除:
我@ home的$ X =SSL01:49188,ssl999999:49188 ,,,,,
我@ home的$禁用了javascript -s extglob
我@ home的$回声$ {X + %%(,)}
SSL01:49188,ssl999999:49188
我会使用 SED
方法,如果变换需要被应用到整个文件,如果目标字符串已经在bash变量bash的子去除方法
How to remove all n characters from a particular string using shell scripts,
ssl01:49188,,,
ssl01:49188,
ssl01:49188,,,,,
ssl01:49188,ssl999999:49188,,,,,
ssl01:49188,abcf999:49188,,,,,
The output will be in the following format
ssl01:49188
ssl01:49188
ssl01:49188
ssl01:49188,ssl999999:49188
ssl01:49188,abcf999:49188
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.
这篇关于使用shell脚本切割最后n个字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!