grep -l 在到 xargs 的管道上的行为不符合预期

grep -l does not behave as expected on piping to xargs

所以我有一个像这样的命令:grep "\"tool\":\"SEETEST\"" * -l 它独立运行时效果很好 - 它打印出为当前目录中的选定工具生成的 JSON 个文件的列表。

但是,如果我像这样将它传送到 xargs ls: grep "\"tool\":\"SEETEST\"" * -l | xargs ls -lSh

打印当前目录下的所有文件!

如何让它只打印匹配的文件名并将它们通过管道传输到 ls 按大小排序?

如果没有 xargs 的匹配项,那么它将列出当前目录中的所有文件:

#----------- current files in the directory
mortiz@florida:~/Documents/projects/bash/test$ ls -ltr
    total 8
    -rw-r--r-- 1 mortiz mortiz 585 Jun 18 12:13 json.example2
    -rw-r--r-- 1 mortiz mortiz 574 Jun 18 12:14 json.example
#----------- using your command
mortiz@florida:~/Documents/projects/bash/test$ grep "\"title\": \"example\"" * -l
json.example
#-----------adding xargs to the previous command
mortiz@florida:~/Documents/projects/bash/test$ grep "\"title\": \"example\"" * -l | xargs ls -lSh
-rw-r--r-- 1 mortiz mortiz 574 Jun 18 12:14 json.example
#-----------adding purposely an error on "title" 
mortiz@florida:~/Documents/projects/bash/test$ grep "\"titleo\": \"example\"" * -l | xargs ls -lSh
total 8.0K
-rw-r--r-- 1 mortiz mortiz 585 Jun 18 12:13 json.example2
-rw-r--r-- 1 mortiz mortiz 574 Jun 18 12:14 json.example

如果你想使用 xargs 并且 grep 没有 return 任何匹配项,那么添加 "-r | --no-run-if-empty" 将阻止 xargs 列出当前目录中的所有文件:

grep "\"titleo\": \"example\"" * -l | xargs -r ls -lSh