例:
file="123 hello"
我怎样才能编辑string文件,使其只包含数字和文本部分被删除?
所以,
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
你可以说:
echo ${file%%[^0-9]*}
但是,在某些情况下会遇到问题:
$ file="123 file 456" $ echo ${file%%[^0-9]*} 123
使用tr
:
$ file="123 hello 456" $ new=$(tr -dc '0-9' <<< $file) $ echo $new 123456