代码之家  ›  专栏  ›  技术社区  ›  Carmageddon

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

  •  0
  • Carmageddon  · 技术社区  · 8 年前

    这个问题已经有了答案:

    所以我有一个命令是: grep "\"tool\":\"SEETEST\"" * -l 这是一个很好的独立工具-它打印出当前目录中为所选工具生成的json文件列表。

    但是,如果我要用管道把它传送到沙格斯,就像这样: grep "\"tool\":\"SEETEST\"" * -l | xargs ls -lSh

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

    如何让它只打印匹配的文件名,并将它们按大小排序到ls?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Miguel Ortiz    8 年前

    如果没有与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没有返回任何匹配项,则添加 "-r | --no-run-if-empty" 这将阻止xargs列出当前目录中的所有文件:

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