【问题标题】:xargs: variable substitution after redirectionxargs:重定向后的变量替换
【发布时间】:2012-02-17 15:43:51
【问题描述】:

我正在尝试查找所有编码为 iso-8859-1 的文本文件并将其转换为 UTF-8。到目前为止,我的尝试是:

find . -name '*.txt' | xargs grep 'iso-8859-1' | cut -d ':' -f1 | 
xargs iconv -f ISO-8859-1 -t UTF-8 {} > {}.converted

(明显的)问题是最后一个变量替换不起作用,因为{} 发生在重定向之后,并且不属于xargs。因为我只得到一个名为{}.converted 的文件,而不是a.txt.convertedb.txt.converted 等。我怎样才能使它工作?

注意:我在 Cygwin 上执行此操作,其中 iconv 似乎不支持 -o

【问题讨论】:

  • 请看看这个related question
  • 我不知道该接受哪个答案。 e.dan 和 glenn 的回答是最务实的,但 Ole Tanges 是最美观的。 chorobas 也相当不错。必须考虑一下。

标签: bash find xargs


【解决方案1】:

如果您安装了 GNU Parallel http://www.gnu.org/software/parallel/,您可以这样做:

find . -name '*.txt' | parallel grep -il iso-8859-1 | parallel iconv -f ISO-8859-1 -t UTF-8 {} \> {}.converted

您可以通过以下方式安装 GNU Parallel:

wget http://git.savannah.gnu.org/cgit/parallel.git/plain/src/parallel
chmod 755 parallel
cp parallel sem

观看 GNU Parallel 的介绍视频以了解更多信息: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

【讨论】:

    【解决方案2】:

    for 循环怎么样:

    for file in `find . -name '*.txt' | xargs grep 'iso-8859-1' | cut -d ':' -f1`; do
        iconv -f ISO-8859-1 -t UTF-8 $file > $file.converted
    done
    

    【讨论】:

    • 您的解决方案将如何处理文件:My brother's 12" records: Listed a->z.txt?
    【解决方案3】:

    假设您的文件名称中没有换行符,并假设您有 GNU find 和 xargs::

    find . -name '*.txt' -print0 |
    xargs -0 grep -l 'iso-8859-1' |
    while read -r file; do
        iconv -f ISO-8859-1 -t UTF-8 "$file" > "$file".converted 
    done
    

    使用grep -l,您不需要在管道中使用cut 命令。

    【讨论】:

      【解决方案4】:

      你快到了:

      find . -name '*.txt' | xargs grep -i iso-8859-1 | cut -f1 -d: | \
      xargs -I% echo iconv -f l1 -t utf8 % \> %.utf | bash
      

      【讨论】:

      • 您的解决方案将如何处理文件:My brother's 12" records: Listed a->z.txt?
      【解决方案5】:

      将您希望 xargs 操作的命令回显到通过管道传输到 shell 的字符串,这将克服替换问题。

      find . -name '*.txt' | xargs grep 'iso-8859-1' | cut -d ':' -f1 | 
      xargs echo "iconv -f ISO-8859-1 -t UTF-8 {} > {}.converted" | bash
      

      【讨论】:

        猜你喜欢
        • 2017-11-17
        • 2020-09-15
        • 2010-10-22
        • 1970-01-01
        • 2019-01-09
        • 1970-01-01
        • 1970-01-01
        • 2016-02-12
        • 1970-01-01
        相关资源
        最近更新 更多