programing

Bash를 사용하여 파일에 특정 문자열이 포함되어 있는지 확인하는 방법

telecom 2023. 5. 10. 20:16
반응형

Bash를 사용하여 파일에 특정 문자열이 포함되어 있는지 확인하는 방법

bash에 특정 문자열이 포함되어 있는지 확인하고 싶습니다.이 스크립트를 사용했지만 작동하지 않습니다.

 if [[ 'grep 'SomeString' $File' ]];then
   # Some Actions
 fi

내 코드에 무슨 문제가 있습니까?

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

필요없습니다[[ ]]명령을 직접 실행하십시오.더하다-q문자열을 찾을 때 표시할 필요가 없는 경우 옵션을 선택합니다.

grep명령은 검색 결과에 따라 종료 코드에서 0 또는 1을 반환합니다. 무언가가 발견되면 0을 반환하고, 그렇지 않으면 1을 반환합니다.

$ echo hello | grep hi ; echo $?
1
$ echo hello | grep he ; echo $?
hello
0
$ echo hello | grep -q he ; echo $?
0

다음 조건으로 명령을 지정할 수 있습니다.if종료 코드에서 명령이 0을 반환하면 조건이 참이고 그렇지 않으면 거짓입니다.

$ if /bin/true; then echo that is true; fi
that is true
$ if /bin/false; then echo that is true; fi
$

여기서 프로그램을 직접 실행하는 것입니다.추가 없음[]또는[[]].

파일에 특정 문자열이 포함되어 있지 않은지 확인하고자 하는 경우 다음과 같이 할 수 있습니다.

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

여러분이 원하는 것을 하는 방법을 알려준 다른 대답 외에도, 저는 무엇이 잘못되었는지(여러분이 원하는 것이 무엇인지) 설명하려고 노력합니다.

바시에서,if명령을 따라야 합니다.이 명령의 종료 코드가 0이면,then부품이 실행됩니다. 그렇지 않으면else실행된 부분이 있는 경우.

다른 답변에 설명된 대로 모든 명령을 사용하여 이 작업을 수행할 수 있습니다.if /bin/true; then ...; fi

[[는 파일 존재, 변수 비교와 같은 일부 테스트 전용 내부 bash 명령입니다.유사하게[외부 명령입니다(일반적으로 위치)./usr/bin/[거의 동일한 테스트를 수행하지만 필요한 경우]마지막 주장으로서, 그것이 이유입니다.]왼쪽에 공백을 채워야 합니다. 이것은 그렇지 않습니다.]].

여기서 할 필요가 없습니다.[[도 아니다[.

또 다른 것은 인용하는 방식입니다.bash에서 인용문 쌍이 둥지를 튼 경우는 단 한 가지입니다."$(command "argument")"하지만'grep 'SomeString' $File'당신은 오직 한 단어를 가지고 있습니다, 왜냐하면'grep '에 연결된 인용 단위입니다.SomeString그리고 다시 연결되었습니다.' $File'변수$File작은 따옴표를 사용하기 때문에 값으로 대체되지도 않습니다.그렇게 하는 적절한 방법은grep 'SomeString' "$File".

최단(올바른) 버전:

grep -q "something" file; [ $? -eq 0 ] && echo "yes" || echo "no"

라고도 쓸 수 있습니다.

grep -q "something" file; test $? -eq 0 && echo "yes" || echo "no"

그러나 이 경우에는 명시적으로 테스트할 필요가 없으므로 다음과 같습니다.

grep -q "something" file && echo "yes" || echo "no"
##To check for a particular  string in a file

cd PATH_TO_YOUR_DIRECTORY #Changing directory to your working directory
File=YOUR_FILENAME  
if grep -q STRING_YOU_ARE_CHECKING_FOR "$File"; ##note the space after the string you are searching for
then
echo "Hooray!!It's available"
else
echo "Oops!!Not available"
fi
grep -q [PATTERN] [FILE] && echo $?

종료 상태는 다음과 같습니다.0(true) 패턴이 발견된 경우에는 (true), 그렇지 않은 경우에는 빈 문자열입니다.

if grep -q [string] [filename]
then
    [whatever action]
fi

if grep -q 'my cat is in a tree' /tmp/cat.txt
then
    mkdir cat
fi

문자열이 전체 줄과 일치하는지, 고정 문자열인지 확인하고 싶은 경우 다음과 같이 할 수 있습니다.

grep -Fxq [String] [filePath]

 searchString="Hello World"
 file="./test.log"
 if grep -Fxq "$searchString" $file
    then
            echo "String found in $file"
    else
            echo "String not found in $file"
 fi

man 파일에서:

-F, --fixed-strings

          Interpret  PATTERN  as  a  list of fixed strings, separated by newlines, any of 

which is to be matched.
          (-F is specified by POSIX.)
-x, --line-regexp
          Select only those matches that exactly match the whole line.  (-x is specified by 

POSIX.)
-q, --quiet, --silent
          Quiet; do not write anything to standard output.  Exit immediately with zero 

status  if  any  match  is
          found,  even  if  an error was detected.  Also see the -s or --no-messages 

option.  (-q is specified by
          POSIX.)

사용해 보십시오.

if [[ $(grep "SomeString" $File) ]] ; then
   echo "Found"
else
   echo "Not Found"
fi

제가 한 일입니다. 잘 되는 것 같습니다.

if grep $SearchTerm $FileToSearch; then
   echo "$SearchTerm found OK"
else
   echo "$SearchTerm not found"
fi
grep -q "something" file
[[ !? -eq 0 ]] && echo "yes" || echo "no"

언급URL : https://stackoverflow.com/questions/11287861/how-to-check-if-a-file-contains-a-specific-string-using-bash

반응형