How can I match a string with a regex in Bash?

后端 未结 6 1159
囚心锁ツ
囚心锁ツ 2020-12-02 05:04

I am trying to write a bash script that contains a function so when given a .tar, .tar.bz2, .tar.gz etc. file it uses tar with the rel

6条回答
  •  死守一世寂寞
    2020-12-02 05:09

    A Function To Do This

    extract () {
      if [ -f $1 ] ; then
          case $1 in
              *.tar.bz2)   tar xvjf $1    ;;
              *.tar.gz)    tar xvzf $1    ;;
              *.bz2)       bunzip2 $1     ;;
              *.rar)       rar x $1       ;;
              *.gz)        gunzip $1      ;;
              *.tar)       tar xvf $1     ;;
              *.tbz2)      tar xvjf $1    ;;
              *.tgz)       tar xvzf $1    ;;
              *.zip)       unzip $1       ;;
              *.Z)         uncompress $1  ;;
              *.7z)        7z x $1        ;;
              *)           echo "don't know '$1'..." ;;
          esac
      else
          echo "'$1' is not a valid file!"
      fi
    }
    

    Other Note

    In response to Aquarius Power in the comment above, We need to store the regex on a var

    The variable BASH_REMATCH is set after you match the expression, and ${BASH_REMATCH[n]} will match the nth group wrapped in parentheses ie in the following ${BASH_REMATCH[1]} = "compressed" and ${BASH_REMATCH[2]} = ".gz"

    if [[ "compressed.gz" =~ ^(.*)(\.[a-z]{1,5})$ ]]; 
    then 
      echo ${BASH_REMATCH[2]} ; 
    else 
      echo "Not proper format"; 
    fi
    

    (The regex above isn't meant to be a valid one for file naming and extensions, but it works for the example)

提交回复
热议问题