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

例子:

file="123 hello"

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

所以,

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

要将结果保存到变量本身,请执行以下操作

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

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

https://stackoverflow.com/questions/19724531/

相关文章:

linux - 如何从目录复制内容而不是符号链接(symbolic link)?

linux - 在 Linux 中的特定行向文件添加文本

linux - 如何获取unix数据文件中每行的前n个字符

linux - Elasticsearch 无法写入日志文件

c - 为什么 mmap() 比顺序 IO 快?

regex - 在 Linux 中,名称与正则表达式匹配的文件的磁盘使用情况?

linux - 如何将 ISO8859-15 转换为 UTF8?

linux - 无法覆盖符号链接(symbolic link) RedHat Linux

python - 比较两个图像的 python/linux 方式

linux - 尾部反转/打印除最后 n 行之外的所有内容?