【问题标题】:How to concatenate extra value to output of one command and pass it to another Unix command如何将额外值连接到一个命令的输出并将其传递给另一个 Unix 命令
【发布时间】:2014-01-09 19:23:34
【问题描述】:

我有这个命令

grep 'Some pattern' location/*filename* | cut -d ' ' -f2 | cut -d '}' -f2 |
grep -v '^$' | head -1

上面的命令给了我一些文件名的输出,例如:

abc.txt

现在我想从这个文件 abc.txt 中 grep 另一行匹配一些特定的模式,所以我这样做了

grep 'some pattern' location/*filename* | grep -iv .tar | grep -v backup |
grep -v bkp | cut -d ' ' -f2 | cut -d '}' -f2 | head -1 | xargs grep 'some pattern'

它不起作用,因为abc.txt 文件不在我的当前目录中。

谁能告诉我如何将位置路径附加到abc.txt,然后再将其传递给xargs grep 命令?

【问题讨论】:

  • 请不要建议我编写脚本并将值存储到某个变量中。我可以这样做,但我不能编写脚本和使用变量
  • 请发布您的数据,以及您喜欢其中的内容以及获取方式。这将有助于我们了解您的问题,并使我们能够为您提供帮助。
  • @Jotne 我无法发布数据,但我可以解释更多。我在一个目录中有文件.. dev/temp/code/steps/ 我得到一个文件名(abc.txt)来自上面的目录使用我的第一个命令。现在 abc.txt 存在于另一个目录中,假设 dev/temp/text/ 现在我想像在上面的命令中那样从这个 abc.txt 中 grep 一行。

标签: linux bash unix grep xargs


【解决方案1】:

你可以试试这个,

grep 'some pattern' location/*filename* | grep -iv .tar | grep -v backup |
grep -v bkp | cut -d ' ' -f2 | cut -d '}' -f2 | head -1 | xargs |
sed 's#.*#/path/to/dir/&#g' | xargs grep 'some pattern'

【讨论】:

  • 为什么是空的xargs
【解决方案2】:

如果cmd 产生输出“bar”,但您想要“foobar”,您可以这样做:

printf foo; cmd

在您的情况下,如果您想在输出前添加 /p/a/t/h,只需执行以下操作:

{ printf /p/a/t/h/; grep 'some pattern' filename | ... | head -1; } | xargs ...

但您最好将head -1 替换为sed -e 1s@^@/p/a/t/h/@ -e 1q

【讨论】:

    【解决方案3】:

    从表面上看,如果第一个命令序列给出了某个目录中的文件名,则需要使用find 来获取文件的路径名:

    find . -type f -name $(grep 'Some pattern' location/*filename* | cut -d ' ' -f2 |
                           cut -d '}' -f2 | grep -v '^$' | head -1) \
         -exec grep 'some pattern' {} +
    

    你不需要在第一行后面加上反斜杠(尽管它不会造成伤害);您确实需要第二行之后的反斜杠。您可以为搜索指定一个不同于. 的起点。

    【讨论】:

    • 我有文件路径,所以不需要找到它..它会增加时间..我只需要附加文件路径并将其用于下一个命令..谢谢你回答给我提示我找到了我的解决方案。请检查我的答案
    • 如果你知道路径,那你就写grep 'some pattern' path/to/abc.txt,不是吗?
    • 但我正在从另一个命令中获取 abc.txt ......正如我的问题中提到的那样
    【解决方案4】:

    大家好,感谢您的建议..无论如何我也找到了解决我的问题的方法..

    仅供参考

    这是我用的..

    echo "dev/temp/text/"$(grep 'Some pattern' location/*filename* | cut -d ' ' -f2 | cut -d '}' -f2 | grep -v '^$' | head -1) | xarg grep 'some pattern'
    

    【讨论】:

      【解决方案5】:

      几个想法:

      ... | head -1 | sed 's,^,location/,' | xargs grep 'some pattern'
      

      ... | head -1 | xargs -I FILE grep 'some pattern' location/FILE
      

      【讨论】:

        猜你喜欢
        • 2013-11-08
        • 2016-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多