當我執行此命令時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 中使用 shell 通配符 ( ),其中單一字元的通配符是點 ( .
)。的模式.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
答案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"
您可以使用和 use建立臨時檔案grep --color=always
來查看上述模式如何更改輸出。
順便說一句,解析ls
通常不是一個好主意,最好使用find
:
find /path/to/files/ -maxdepth 1 -type f -iname '*.jpg'