grep 패턴 검색 관련 질문입니다.

khalisto의 이미지

안녕하세요. grep 패턴 사용중 아래와같은 경우에서도 조건 검색이 되는지 질문드립니다.

list.txt 파일의 내용이 아래와 같고

5000 apple
10000 pineapple

cat list.txt | grep apple 명령어를 실행하게되면

5000 apple
10000 pineapple

와 같이 apple 패턴이 포함된 모든 행이 출력되는데 grep 정규식에서 ^는 행의 시작이 매칭되는것

^apple 이면 apple 로 행이 시작되어야하지만 list.txt 에서는 5000 뒤에 apple 이 명시되어

있으므로 검색이 되지 않았으며 apple$ 로 검색하게 되면 apple 과 pineapple 이 모두 출력됩니다.

apple로 끝나니 당연한 거겠지만요. ^apple$ 의 경우는 apple로 시작과 끝나는경우라

아예 출력이 되지 않구요.

원하는 검색결과는 list.txt 파일 내용중 apple 만을 출력하고자 하는 것인데 어떠한

정규식을 사용해야 이것이 가능할까요??

고수님들의 의견 부탁드립니다.

Prentice의 이미지

grep "\bapple\b" list.txt
grep -o "\bapple\b" list.txt
khalisto의 이미지

원하는 결과대로 잘 출력됩니다. 너무 감사드립니다.

그런데 \b 의 의미에 대해 알수 있을까요?

Prentice의 이미지

\b는 zero-width match에 해당하며, 이는 특정 글자가 아니라 "글자와 글자 사이의 위치"로 검색에 걸린다는 걸 뜻합니다.

\b는 "단어"의 시작이나 끝의 위치를 찾을 때 사용하시면 됩니다.

qiiiiiiiip의 이미지

이 경우는 간단하게
grep -w apple list.txt
라고 해도 됩니다.

       -w, --word-regexp
              Select only those lines containing matches that  form  whole  words.   The  test  is  that  the
              matching  substring  must  either  be  at  the beginning of the line, or preceded by a non-word
              constituent character.  Similarly, it must be either at the end of the line or  followed  by  a
              non-word  constituent  character.   Word-constituent  characters  are  letters, digits, and the
              underscore.