Return a regex match in a Bash script, instead of replacing it

前端 未结 9 760
面向向阳花
面向向阳花 2021-01-31 04:30

I just want to match some text in a Bash script. I\'ve tried using sed but I can\'t seem to make it just output the match instead of replacing it with something.



        
相关标签:
9条回答
  • 2021-01-31 04:58

    I Know this is an old topic but I came her along same searches and found another great possibility apply a regex on a String/Variable using grep:

    # Simple
    $(echo "TestT100String" | grep -Po "[0-9]{3}")
    # More complex using lookaround
    $(echo "TestT100String" | grep -Po "(?i)TestT\K[0-9]{3}(?=String)")
    

    With using lookaround capabilities search expressions can be extended for better matching. Where (?i) indicates the Pattern before the searched Pattern (lookahead), \K indicates the actual search pattern and (?=) contains the pattern after the search (lookbehind).

    https://www.regular-expressions.info/lookaround.html

    The given example matches the same as the PCRE regex TestT([0-9]{3})String

    0 讨论(0)
  • 2021-01-31 04:59

    using awk

    linux$ echo -E "TestT100String" | awk '{gsub(/[^0-9]/,"")}1'
    100
    
    0 讨论(0)
  • 2021-01-31 05:00
    echo "TestT100String" | sed 's/[^0-9]*\([0-9]\+\).*/\1/'
    
    echo "TestT100String" | grep -o  '[0-9]\+'
    

    The method you use to put the results in an array depends somewhat on how the actual data is being retrieved. There's not enough information in your question to be able to guide you well. However, here is one method:

    index=0
    while read -r line
    do
        array[index++]=$(echo "$line" | grep -o  '[0-9]\+')
    done < filename
    

    Here's another way:

    array=($(grep -o '[0-9]\+' filename))
    
    0 讨论(0)
提交回复
热议问题