从shell脚本中的变量中删除非ascii字符

Sud*_*dar 1 shell non-ascii-characters

我在shell脚本中输出命令的输出并将结果存储在变量中.

由于grep使用的解析逻辑,这个变量可能具有非ascii字符,这是一个非常极端的情况.

问题:如何从shell脚本中的此变量中删除这些非ascii字符,以便我可以在后续命令中使用该变量?

gni*_*urf 6

如果你正在使用bash,并且如果你的变量被调用var,那么

"${var//[^[:ascii:]]/}"
Run Code Online (Sandbox Code Playgroud)

将扩展为var删除所有非ascii字符.所以:

var_non_ascii=${var//[^[:ascii:]]/}
Run Code Online (Sandbox Code Playgroud)

应该做.(这绝对是最好的方法:没有子shell,也没有外部进程的bash for bash).