Linux 如何从 Bash 中的字符串中删除所有非数字字符?

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

How to remove all non-numeric characters from a string in Bash?

linuxbashshellubuntuterminal

提问by Ayush Mishra

Example:

例子:

file="123 hello"

How can I edit the string filesuch that it only contains the numbers and the text part is removed?

如何编辑字符串file,使其仅包含数字并删除文本部分?

So,

所以,

echo $file

should print 123only.

应该123只打印。

回答by fedorqui 'SO stop harming'

This is one way with sed:

这是一种方式sed

$ echo $file | sed 's/[^0-9]*//g' 
123
$ echo "123 he23llo" | sed 's/[^0-9]*//g'
12323

Or with pure bash:

或者用纯bash

$ echo "${file//[!0-9]/}" 
123
$ file="123 hello 12345 aaa"
$ echo "${file//[!0-9]/}"?
12312345

To save the result into the variable itself, do

要将结果保存到变量本身,请执行

$ file=$(echo $file | sed 's/[^0-9]*//g')
$ echo $file
123

$ file=${file//[!0-9]/}
$ echo $file
123

回答by devnull

You can say:

你可以说:

echo ${file%%[^0-9]*}

However, this runs into problems in certain cases:

但是,这在某些情况下会遇到问题:

$ file="123 file 456"
$ echo ${file%%[^0-9]*}
123

Using tr:

使用tr

$ file="123 hello 456"
$ new=$(tr -dc '0-9' <<< $file)
$ echo $new
123456