【问题标题】:Pass stdin as argument in sed将标准输入作为参数传递给 sed
【发布时间】:2016-04-09 01:17:52
【问题描述】:

如果我们必须查找文件,计算 md5 代码,然后将其放入文本文件,我必须编写一个命令。查找文件并不难,只是

find -type f

现在我有一个文件列表,我必须为每个文件找到 md5 代码。我知道生成 md5 代码的代码

openssl dgst -md5 <file>

但是我如何使用管道(无脚本)来拥有这样的东西`

filename md5code

我已经试过了

while read line do... done

但这没有用。我认为我必须使用 sed,但我现在不知道如何使用。我最近的尝试(我认为)是这样的:

find dir -type f | sed "s/^\(.*\)$/\1 $( openssl dgst -md5 \1 )/" >> file.txt

但它不识别 \1...

我尝试使用 find 中的 -exec 选项,如下所示:

md5$ find dir -type f -exec sed "s/^\(.*\)$/\1 $( openssl dgst -md5 {} )/" \;

但它无法识别 {}

【问题讨论】:

    标签: shell unix sed command stdin


    【解决方案1】:

    您可以使用xargs 命令处理find 命令返回的文件列表。

    find dir -type f | xargs md5sum >> file.txt
    

    大多数类 Unix 操作系统都应该安装 md5sum 实用程序,所以我使用它而不是 openssl dgst -mdxargs 命令将文件列表作为输入,然后通过将这些文件用作md5sum 命令的参数来构建命令。

    如果您的文件名包含空格或其他不常见的字符,则需要使用:

    find dir -type f -print0 | xargs -0 md5sum >> file.txt
    

    -print0 选项使用 NULL 字符分隔find 命令返回的文件列表,xargs-0, --null 选项告诉它使用 NULL 而不是空格来分隔输入项。

    注意:这将适用于这些工具的 GNU 版本。我不知道其他版本,因为它没有被POSIX specification for find 采用。

    【讨论】:

      【解决方案2】:

      您的命令替换在单引号内不起作用,但我建议使用-exec 开关而不是管道。你也可以使用-print(或者-printf,如果你的find版本支持的话),尽管文件名包含在我系统上openssl命令的输出中,所以也许你不需要它。试试这个:

      find . -type f -printf '%f ' -exec openssl dgst -md5 {} \;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-14
        • 1970-01-01
        • 2013-02-03
        • 2020-12-23
        • 1970-01-01
        相关资源
        最近更新 更多