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.NOTAJPGNOTAJPG.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'

関連情報