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

后端 未结 2 1894
攒了一身酷
攒了一身酷 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:06

    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:

    $ file="123 hello 456"
    $ new=$(tr -dc '0-9' <<< $file)
    $ echo $new
    123456
    

提交回复
热议问题