How to extract numbers from a string?

前端 未结 10 1947
青春惊慌失措
青春惊慌失措 2020-12-10 04:20

I have string contains a path

string=\"toto.titi.12.tata.2.abc.def\"

I want to extract only the numbers from this string.

To extrac

相关标签:
10条回答
  • 2020-12-10 04:55

    This would be easier to answer if you provided exactly the output you're looking to get. If you mean you want to get just the digits out of the string, and remove everything else, you can do this:

    d@AirBox:~$ string="toto.titi.12.tata.2.abc.def"
    d@AirBox:~$ echo "${string//[a-z,.]/}"
    122
    

    If you clarify a bit I may be able to help more.

    0 讨论(0)
  • 2020-12-10 04:57

    You can also use sed:

    echo "toto.titi.12.tata.2.abc.def" | sed 's/[0-9]*//g'
    

    Here, sed replaces

    • any digits (class [0-9])
    • repeated any number of times (*)
    • with nothing (nothing between the second and third /),
    • and g stands for globally.

    Output will be:

    toto.titi..tata..abc.def
    
    0 讨论(0)
  • 2020-12-10 04:58

    Hi adding yet another way to do this using 'cut',

    echo $string | cut -d'.' -f3,5 | tr '.' ' '
    

    This gives you the following output: 12 2

    0 讨论(0)
  • 2020-12-10 04:59

    To extract all the individual numbers and print one number word per line pipe through -

    tr '\n' ' ' | sed -e 's/[^0-9]/ /g' -e 's/^ *//g' -e 's/ *$//g' | tr -s ' ' | sed 's/ /\n/g'
    

    Breakdown:

    • Replaces all line breaks with spaces: tr '\n' ' '
    • Replaces all non numbers with spaces: sed -e 's/[^0-9]/ /g'
    • Remove leading white space: -e 's/^ *//g'
    • Remove trailing white space: -e 's/ *$//g'
    • Squeeze spaces in sequence to 1 space: tr -s ' '
    • Replace remaining space separators with line break: sed 's/ /\n/g'

    Example:

    echo -e " this 20 is 2sen\nten324ce 2 sort of" | tr '\n' ' ' | sed -e 's/[^0-9]/ /g' -e 's/^ *//g' -e 's/ *$//g' | tr -s ' ' | sed 's/ /\n/g'
    

    Will print out

    20
    2
    324
    2
    
    0 讨论(0)
  • 2020-12-10 05:02

    Here is a short one:

    string="toto.titi.12.tata.2.abc.def"
    id=$(echo "$string" | grep -o -E '[0-9]+')
    
    echo $id // => output: 12 2
    

    with space between the numbers. Hope it helps...

    0 讨论(0)
  • 2020-12-10 05:05

    You can use tr to delete all of the non-digit characters, like so:

    echo toto.titi.12.tata.2.abc.def | tr -d -c 0-9
    
    0 讨论(0)
提交回复
热议问题