grep "*.JPG"가 .JPG로 끝나는 항목을 반환하지 않습니다.

grep "*.JPG"가 .JPG로 끝나는 항목을 반환하지 않습니다.

이 명령을 실행하면 ls -l Documents/phone_photo_vids다음 형식으로 100개의 항목이 표시됩니다. 이미지의 끝이 PNG 또는 JPG인지 확인하세요.

-rw-r--r--  1 moi  staff      189280 Oct 29  2011 IMG_0041.PNG
-rw-r--r--  1 moi staff     2481306 Oct 29  2011 IMG_0042.JPG

그런 다음 jpg 결과만 보고 싶다고 결정하여 두 명령을 모두 실행했지만 둘 다 결과가 반환되지 않았습니다.

 ls -l Documents/phone_photo_vids | grep "*.JPG"
 ls -l Documents/phone_photo_vids | grep "*.JPG$"

나는 두 grep 명령 모두 PNG로 끝나는 모든 파일을 필터링하고 JPG로 끝나는 모든 파일을 반환할 것으로 기대했지만 아무것도 얻지 못했습니다. grep을 어떻게 잘못 사용하고 있나요?

저는 Mac OSX 10.9.3을 사용하고 있습니다.

답변1

어떤 형태의 답변은 다음과 같습니다.잘못된대부분의 경우 주장하는 것처럼 작동하지만.

grep ".jpg"    #match string "jpg" anywhere in the filename with any character in front of it.
               # jpg -- not match
               # .jpg -- match
               # mjpgsfdfd -- match
grep ".*.jpg"  #basically the same thing as above
grep ".jpg$"   #match anything that have at least 4 chars and end with "jpg"
               # i_am_not_a_.dummy_jpg -- match
grep ".*.jpg$" #the same as above (basically)

따라서 최상의 결과를 얻으려면 다음을 시도해 보십시오.

grep "[.]jpg$" #anything that end with ".jpg"
grep "\\.jpg$" #the same as above, use escape sequence instead

답변2

다른 사람들이 말했듯 *이 grep 내에서 쉘 와일드카드( )를 사용하려고 합니다. 여기서 단일 문자에 대한 와일드카드는 점( .)입니다. 패턴이 .JPG일치 xxx.NOTAJPG하거나 NOTAJPG.txt그런 것이 있었다면.

더 나은 해결책은 다음과 같이 말하는 것입니다.

ls -l Documents/phone_photo_vids/*.jpg

대소문자를 구분하지 않으려는 경우

ls Documents/phone_photo_vids/*.{jpg,JPG}

ls라고 말하는 것과 똑같습니다*.jpg *.JPG

권장되지는 않지만 만약에정말로 작업하려면 grep로 끝나는 파일을 지정 jpg하고 로 대소문자를 구분하지 않도록 설정하면 됩니다 -i. 모든 것이 필요하지 않습니다 '.*.'.

ls -l Documents/phone_photo_vids | grep -i jpg$

답변3

Grep은 DOS나 Windows가 검색에 사용하는 것이 아니라 정규식이라는 것을 사용합니다.

정규식 "*.JPG$"는 grep에 적합하지 않으므로 아마도 무시될 것입니다. 원하는 것은 ".*JPG$"입니다.

을 위한참조.

답변4

다음을 시도해 보세요:

grep "jpg"    #match string "jpg" anywhere in the filename, so file "img.jpg.txt" match too
grep ".*jpg"  #match the whole line with string "jpg", here ".*" stands for any char zero or more times
grep "jpg$"   #match string "jpg" only at the end of line ("img.jpg.txt" will not match)
grep ".*jpg$" #match the whole line only if "jpg" is at the end of line
grep "\.jpg"  #match string ".jpg" - to search literaly for dot one need to escape it with backslash

위의 패턴이 출력을 어떻게 변경하는지 확인하기 위해 임시 파일을 만들고 touch "img.jpg.txt" ".jpg"사용할 수 있습니다.grep --color=always

그런데, 구문 분석은 ls일반적으로 좋은 생각이 아니며 더 잘 사용합니다 find.

find /path/to/files/ -maxdepth 1 -type f -iname '*.jpg'

관련 정보