Shell Script 에서 String 다루기

KiJeong·2022년 4월 21일
0

Bash Script

목록 보기
1/4

문자열 찾기

1. 특정 파일에 찾으려는 문자열이 포함되어있는지 확인

if grep -q SomeString "$File"; then
    Some Actions # SomeString was found
fi
  • grep-q 옵션: 화면에 표시하지 않겠다.

포함되어 있지 않은걸 확인하려면 간단히 맨 앞에 ! (not) 만 붙여주면 된다.

if ! grep -q SomeString "$File"; then
  Some Actions # SomeString was not found
fi



2. 특정 명령의 output 으로 찾으려는 문자열이 포함되어있는지 확인

./somecommand | grep 'string' &> /dev/null
if [ $? == 0 ]; then
    echo "matched"
fi

또는

if ./somecommand | grep -q 'string'; then
   echo "matched"
fi



3. 특정 문자열에서 찾으려는 대상 문자열이 포함되어있는지 확인

string='My long string'
if [[ $string == *"My long"* ]]; then
    echo "It's there!"
fi

0개의 댓글