如何从 Bash 中的字符串中删除所有非数字字符? [英] How to remove all non-numeric characters from a string in Bash?

查看:43
本文介绍了如何从 Bash 中的字符串中删除所有非数字字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

file="123 hello"

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

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

或者使用纯 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

这篇关于如何从 Bash 中的字符串中删除所有非数字字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆