我正在學習擴展/命令替換,在查看範例時,注意到這兩個命令有不同的結果。
例如,如果我 cd 進入/usr/bin
,然後運行ls | grep zip
,grep 只會在檔案名稱中選取“zip”。
但是當我grep zip $(ls)
在同一目錄中運行時,grep 也會在檔案內容中取得 zip。為什麼?烏班圖16.04。
我知道這是一個新手問題,但了解原因仍然會有所幫助。謝謝。
答案1
這是因為grep
可以以兩種不同的模式運作:
DESCRIPTION grep searches the named input FILEs for lines containing a match to the given PATTERN. If no files are specified, or if the file “-” is given, grep searches standard input. By default, grep prints the matching lines.
在 中ls | grep zip
,該grep
命令在其標準輸入上看到文件名列表並對其進行搜尋。
在 中grep zip $(ls)
,shell 將ls
命令的結果替換為列表單詞,該列表grep
單字被視為檔案名稱參數,依序搜尋每個單字的模式zip
。
重要提示:如果任何檔案名稱包含空格,則空格分隔的部分將被視為單獨的參數,從而導致 No such file or directory
錯誤。搜尋匹配檔案的更安全方法是使用 shell glob,例如grep 'pattern' *zip*