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

时间:2022-12-14 09:38:01

Example:

例:

file="123 hello"

How can i edit the string file such that it only contains the numbers and the text part is removed?

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

So,

所以,

echo $file

should print 123 only.

应该只打印123。

2 个解决方案

#1


57  

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

#2


4  

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

#1


57  

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

#2


4  

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