How to remove all non-numeric characters from a string in Bash?

后端 未结 2 1904
攒了一身酷
攒了一身酷 2020-12-23 21:35

Example:

file=\"123 hello\"

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

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-23 22:10

    This is one way with sed:

    $ echo $file | sed 's/[^0-9]*//g' 
    123
    $ echo "123 he23llo" | sed 's/[^0-9]*//g'
    12323
    

    Or with pure 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
    

提交回复
热议问题