Extract pattern from a string

前端 未结 5 2124
耶瑟儿~
耶瑟儿~ 2020-12-16 02:21

In bash script, what is the easy way to extract a text pattern from a string?

For example, I want to extract X followed by 2 digits in the end of the st

相关标签:
5条回答
  • 2020-12-16 02:31

    There's a nifty =~ regex operator when you use double square brackets. Captured groups are made available in the $BASH_REMATCH array.

    if [[ $STRING =~ (X[0-9]{2})$ ]]; then
        echo "matched part is ${BASH_REMATCH[1]}"
    fi
    
    0 讨论(0)
  • 2020-12-16 02:32

    You can also use parameter expansion:

    V="abcX23"
    PREFIX=${V%%X[0-9][0-9]} # abc
    SUFFIX=${V:${#PREFIX}}   # X23
    
    0 讨论(0)
  • 2020-12-16 02:41

    Lets take your input as

    Input.txt

    ASD123
    GHG11D3456
    FFSD11dfGH
    FF87SD54HJ
    

    And the pattern I want to find is "SD[digit][digit]"

    Code

    grep -o 'SD[0-9][0-9]' Input.txt

    Output

    SD12
    SD11
    SD54
    

    And if you want to use this in script...then you can assign the above code in a variable/array... that's according to your need.

    0 讨论(0)
  • 2020-12-16 02:42
    $ foo="abcX23"
    $ echo "$(echo "$foo" | sed 's/.*\(X[0-9][0-9]\)$/\1/')"
    X23
    

    or

    if [[ "$foo" =~ X[0-9][0-9]$ ]]; then
      echo "${foo:$((${#foo}-3))}"
    fi
    
    0 讨论(0)
  • 2020-12-16 02:46

    I need to extract the host port from this string: NIC 1 Rule(0): name = guestssh, protocol = tcp, host ip = , host port = 2222, guest ip = , guest port = 22

    That string is obtained by using: vboxmanage showvminfo Mojave | grep 'host port', I mean is filtered and I need to extract whatever number be in the host port; in this case is 2222 but it can be different.

    0 讨论(0)
提交回复
热议问题