Program Tip

case 문에서 패턴을 사용하는 방법은 무엇입니까?

programtip 2020. 10. 31. 10:02
반응형

case 문에서 패턴을 사용하는 방법은 무엇입니까?


man페이지는 case명령문이 "파일 이름 확장 패턴 일치"를 사용 한다고 말합니다 .
일반적으로 일부 매개 변수에 대한 짧은 이름을 원하므로 다음으로 이동합니다.

case $1 in
    req|reqs|requirements) TASK="Functional Requirements";;
    met|meet|meetings) TASK="Meetings with the client";;
esac

logTimeSpentIn "$TASK"

내가 좋아하는 패턴을 시도 req*하거나 me{e,}t하는 내가 파일명 확장의 맥락에서 그 값과 일치하도록 정확하게 확장 것 이해하지만, 그것은 작동하지 않습니다.


중괄호 확장은 작동하지 않지만 *, ?[]않습니다. 설정 shopt -s extglob하면 확장 패턴 일치를 사용할 수도 있습니다 .

  • ?() -0 개 또는 1 개의 패턴 발생
  • *() -0 개 이상의 패턴 발생
  • +() -하나 이상의 패턴 발생
  • @() -패턴 발생 1 회
  • !() -패턴을 제외한 모든 것

예를 들면 다음과 같습니다.

shopt -s extglob
for arg in apple be cd meet o mississippi
do
    # call functions based on arguments
    case "$arg" in
        a*             ) foo;;    # matches anything starting with "a"
        b?             ) bar;;    # matches any two-character string starting with "b"
        c[de]          ) baz;;    # matches "cd" or "ce"
        me?(e)t        ) qux;;    # matches "met" or "meet"
        @(a|e|i|o|u)   ) fuzz;;   # matches one vowel
        m+(iss)?(ippi) ) fizz;;   # matches "miss" or "mississippi" or others
        *              ) bazinga;; # catchall, matches anything not matched above
    esac
done

중괄호를 사용할 수 없다고 생각합니다.

조건부 구성의 경우에 대한 Bash 매뉴얼에 따르면 .

패턴 은 물결표 확장, 매개 변수 확장, 명령 대체 및 산술 확장을 거칩니다.

불행히도 Brace Expansion 에 대해서는 아무것도 없습니다 .

따라서 다음과 같이해야합니다.

case $1 in
    req*)
        ...
        ;;
    met*|meet*)
        ...
        ;;
    *)
        # You should have a default one too.
esac

ifgrep -Eq

arg='abc'
if echo "$arg" | grep -Eq 'a.c|d.*'; then
  echo 'first'
elif echo "$arg" | grep -Eq 'a{2,3}'; then
  echo 'second'
fi

어디:

  • -qgrep출력 생성을 방지 하고 종료 상태 만 생성합니다.
  • -E 확장 정규식을 활성화합니다.

나는 이것을 좋아하기 때문에 :

One downside is that this is likely slower than case since it calls an external grep program, but I tend to consider performance last when using Bash.

case is POSIX 7

Bash appears to follow POSIX by default without shopt as mentioned by https://stackoverflow.com/a/4555979/895245

Here is the quote: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_01 section "Case Conditional Construct":

The conditional construct case shall execute the compound-list corresponding to the first one of several patterns (see Pattern Matching Notation) [...] Multiple patterns with the same compound-list shall be delimited by the '|' symbol. [...]

The format for the case construct is as follows:

case word in
     [(] pattern1 ) compound-list ;;
     [[(] pattern[ | pattern] ... ) compound-list ;;] ...
     [[(] pattern[ | pattern] ... ) compound-list]
  esac

and then http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13 section "2.13. Pattern Matching Notation" only mentions ?, * and [].

참고URL : https://stackoverflow.com/questions/4554718/how-to-use-patterns-in-a-case-statement

반응형