티스토리 뷰

개발/Shell Script

[sh] 문자열 포함 여부 검사

Jaeyeon Baek 2015. 12. 15. 12:25


shell script 에서 때로는 문자열 패턴의 일치 여부를 확인하는 것이 아니라 포함되는지 확인해야 하는 경우가 있습니다.


아래 예시를 살펴보겠습니다.

AA="My name is oops"
BB="oops"

변수 $BB가 $AA에 포함되는지 확인하는 방법에는 여러가지가 있겠지만 아래 두 가지 방법을 소개합니다. ( Node.js 로 비유하자면 str.includes(word) 같은 역할이겠죠 )


#!/bin/sh

AA="My name is oops"
BB="name"
    
if [[ "$AA" == *"name"* ]];then
    echo "1st find it"
fi  
    
if [[ "$AA" =~ "name" ]];then
    echo "2nd find it"
fi


문자열 패턴을 이용한 * 방법이 있고, =~ 를 이용하는 방법이 존재합니다.


어떤 것이 더 유연한 사용인지는 판단이 서지 않지만 적절하게 사용하도록 합시다.



아래는 =~에 대한 bash의 man페이지 일부 발췌입니다.

An  additional  binary  operator,  =~, is available, with the same precedence as == and !=.  When it is
used, the string to the right of the operator is considered an extended regular expression and  matched
accordingly  (as  in  regex(3)).  The return value is 0 if the string matches the pattern, and 1 other-
wise.  If the regular expression is syntactically incorrect, the conditional expression’s return  value
is 2.  If the shell option nocasematch is enabled, the match is performed without regard to the case of
alphabetic characters.  Any part of the pattern may be quoted to force it to be matched  as  a  string.
Substrings matched by parenthesized subexpressions within the regular expression are saved in the array
variable BASH_REMATCH.  The element of BASH_REMATCH with index 0 is the portion of the string  matching
the  entire  regular expression.  The element of BASH_REMATCH with index n is the portion of the string
matching the nth parenthesized subexpression.


댓글
최근에 올라온 글
최근에 달린 댓글
글 보관함
Total
Today
Yesterday