【问题标题】:trick about xargs and wildcard关于 xargs 和通配符的技巧
【发布时间】:2014-10-26 17:27:27
【问题描述】:

我有两个目录'dir1'和'dir2',我想输出这两个目录的所有内容。因此,我使用 bash 命令 'xargs' 仅通过一个命令行来实现。命令是“echo '1 2' | xargs -d ' ' -I @ -t sh -c 'cat dir@/*'”,但是结果很奇怪。

[u@10 /data1/walter]$ echo '1 2' | xargs -d ' ' -I @ -t  sh -c 'cat dir@/*' 
sh -c cat dir1/*   <<<<  This output is normal
1                  <<<<  This is all content in dir1
sh -c cat dir2     
/*                 <<<< these two lines are odd, it looks like xargs insert a '\n' between 'dir2' and '/*'
cat: dir2: Is a directory    <<<< as a result, 'cat' can't receive argument 'dir2'
sh: line 1: /bin: is a directory   <<<< and command line '/*' is error

【问题讨论】:

  • 尝试使用查找目录*。 Yon 可以访问 find 的手册页,以您想要的方式控制/格式化输出。

标签: bash xargs


【解决方案1】:

echo 自动将换行符附加到其输出中,因此xargs 正在获取两个值来替换@12\n。一个直接的解决方法是使用

禁用换行符
echo -n '1 2' | xargs ...

或(更便携)

printf '1 2' | xargs ...

但是,正如其他人指出的那样,使用 xargs 可能比它需要的更复杂。

【讨论】:

    【解决方案2】:

    也许我错过了你的问题,但你可以简单地将两个目录传递给ls

    ls dir1/* dir2/*
    

    这可以使用brace expansion进行简化:

    ls dir{1,2}/*
    

    【讨论】:

      【解决方案3】:

      您可以简单地指定两个目录:

      ls dir1 dir2
      

      或许

      find dir1 dir2
      

      如果您想要更复杂的解决方案(即跨多个目录查找)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-02
        • 1970-01-01
        • 2010-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多