从 bash 变量中删除非打印字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22045175/
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-18 09:42:53  来源:igfitidea点击:

Remove non printing chars from bash variable

bashvariables

提问by Stepan Loginov

I have some variable $a. This variable have non printing characters (carriage return ^M).

我有一些变量$a。此变量具有非打印字符(回车 ^M)。

>echo $a
some words for compgen
>a+="END"
>echo $a
ENDe words for compgen

How I can remove that char? I know that echo "$a"display it correct. But it's not a solution in my case.

我怎样才能删除那个字符?我知道echo "$a"显示正确。但这不是我的情况的解决方案。

采纳答案by chepner

To remove just the trailing carriage return from a, use

要仅从 中删除尾随回车a,请使用

a=${a%$'\r'}

回答by devnull

You could use tr:

你可以使用tr

tr -dc '[[:print:]]' <<< "$var"

would remove non-printable character from $var.

将从中删除不可打印的字符$var

$ foo=$'abc\rdef'
$ echo "$foo"
def
$ tr -dc '[[:print:]]' <<< "$foo"
abcdef
$ foo=$(tr -dc '[[:print:]]' <<< "$foo")
$ echo "$foo"
abcdef

回答by We Are All Monica

I was trying to send a notification via libnotify, with content that may contain unprintable characters. The existing solutions did not quite work for me (using a whitelist of characters using trworks, but strips any multi-byte characters).

我试图通过 libnotify 发送通知,其内容可能包含不可打印的字符。现有的解决方案对我来说不太适用(使用tr作品的字符白名单,但去除任何多字节字符)。

Here is what worked, while passing the test:

通过测试时,这是有效的:

message=$(iconv --from-code=UTF-8 -c <<< "$message")