如何从BASH中的字符串中删除所有非数字字符?
问题描述:
例如:
file="123 hello"
如何编辑字符串文件,使之只包含数字和文字部分被删除?
How can i edit the string file such that it only contains the numbers and the text part is removed?
因此,
echo $file
应打印 123 仅
答
这是 SED 的一种方法:
$ echo $file | sed 's/[^0-9]*//g'
123
$ echo "123 he23llo" | sed 's/[^0-9]*//g'
12323
或用纯庆典:
$ 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