bash 使用 shell 脚本剪切字符串中的最后 n 个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14338416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:11:47  来源:igfitidea点击:

cutting last n character in a string using shell script

bashshellcut

提问by anish

How to remove all n characters from a particular string using shell scripts,

如何使用 shell 脚本从特定字符串中删除所有 n 个字符,

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

回答by Shawn Chin

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.

要通过指定剪切字符串中的最后 n 个字符来回答问题的标题,您可以使用 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/,*$//'.

但是,根据您的示例,您似乎想要删除所有尾随逗号,在这种情况下,您可以使用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:

或者,对于纯粹的 Bash 解决方案,您可以使用子字符串删除:

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

I would use the sedapproach 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.

sed如果需要将转换应用于整个文件,我会使用这种方法,如果目标字符串已经在 bash 变量中,我会使用bash 子字符串删除方法。

回答by cmbuckley

With sed:

sed

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

回答by Vijay

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
> 

回答by Guru

Using sed:

使用 sed:

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