【问题标题】:Run expand on find results运行展开查找结果
【发布时间】:2011-10-04 09:09:17
【问题描述】:

我正在尝试对find 命令找到的所有文件运行expand shell 命令。我试过 -exec 和 xargs 但都失败了。谁能解释我为什么?我在 Mac 上记录。


find . -name "*.php" -exec expand -t 4 {} > {} \;

这只是创建一个包含所有输出的文件{},而不是覆盖每个找到的文件本身。


find . -name "*.php" -print0 | xargs -0 -I expand -t 4 {} > {}

这只是输出

4 {}
xargs: 4: No such file or directory

【问题讨论】:

    标签: linux unix find expand xargs


    【解决方案1】:

    您的命令不起作用有两个原因。

    1. 输出重定向是由 shell 完成的,而不是 find。这意味着 shell 会将finds 的输出重定向到文件{}
    2. 重定向将立即发生。这意味着文件将在expand 命令读取之前就被写入。所以不可能将命令的输出重定向到输入文件中。

    不幸的是,expand 不允许将其输出写入文件。所以你必须使用输出重定向。如果您使用bash,您可以定义一个执行expandfunction,将输出重定向到一个临时文件并将临时文件移回原始文件之上。问题是find 会运行一个新的shell 来执行expand 命令。

    但是有一个解决办法:

    expand_func () {
      expand -t 4 "$1" > "$1.tmp"
      mv "$1.tmp" "$1"
    }
    
    export -f expand_func
    
    find . -name \*.php -exec bash -c 'expand_func {}' \;
    

    您正在使用export -f 将函数expand_func 导出到子shell。而且您不会使用find -exec 执行expand 本身,而是执行一个新的bash 来执行导出的expand_func

    【讨论】:

      【解决方案2】:

      'expand' 真的不值得麻烦。 您可以只使用 sed:

      find . -name "*.php" | xargs sed -i -e 's/\t/    /g'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-06
        • 2014-06-28
        • 2017-09-10
        • 1970-01-01
        • 2015-03-25
        相关资源
        最近更新 更多