【问题标题】:How can heredocs be used with xargs?heredocs 如何与 xargs 一起使用?
【发布时间】:2015-07-11 17:51:27
【问题描述】:

背景

我希望在发送之前从git archive 输出的一些python 源代码文件中删除任何# TODO cmets。我希望通过将在各种 *nix 操作系统上运行的脚本来执行此操作,因此它应该尽可能符合 POSIX。

我知道find -print0xargs -0 不在基本规范中,但它们似乎很常见,我可以很好地使用它们(除非存在更好的替代方案)。我正在使用ed,因为sed -i 不在就地编辑的基本规范中。假设下面的命令是从一个已经解压的 git 存档的目录中运行的。

我很高兴有一个完整的替代解决方案来剥离# TODO cmets,但为了满足我的好奇心,我还想回答我在使用我提出的命令时遇到的特定问题和。

现有代码

find . -type f -name "*.py" -print0 | xargs -0 -I {} ed -s {} << 'EOF'
,g/^[ \t]*#[ \t]*TODO/d
,s/[ \t]*#[ \t]*TODO//
w
EOF

预期结果

所有以“.py”结尾的文件都被删除了仅包含 TODO cmets 或以 TODO 开头的行尾 cmets 的完整行。

实际结果

(标准输出)

,g/^[ \t]*#[ \t]*TODO/d
,s/[ \t]*#[ \t]*TODO//
w
: No such file or directory

当前理论

我相信&lt;&lt; 'EOF' heredoc 被应用于xargs 而不是ed,我不知道如何解决这个问题。

【问题讨论】:

    标签: find posix xargs heredoc ed


    【解决方案1】:

    修复 &lt;&lt; 'EOF' heredoc 方向需要一些 sh -c 诡计,最终导致更多问题,因此我尝试在完全不需要 heredocs 的情况下重新解决问题。

    我最终登陆:

    inline() {
        # Ensure a file was provided
        in="${1?No input file specified}"
        # Create a temp file location
        tmp="$(mktemp /tmp/tmp.XXXXXXXXXX)"
        # Preserve the original file's permissions
        cp -p "$in" "$tmp"
        # Make $@ be the original command
        shift
        # Send original file contents to stdin, output to temp file
        "$@" < "$in" > "$tmp"
        # Move modified temp file to original location, with permissions and all
        mv -f "$tmp" "$in"
    }
    
    find . -type f -name "*.py" -exec grep -ilE '#[ \t]*TODO' {} \+ | while read file; do
        inline "$file" sed -e '/^[ \t]*#[ \t]*TODO/ d' -e 's/[ \t]*#[ \t]*TODO//'
    done
    

    mktemp 在技术上不在基本规范中,但appears to be fairly portable 所以我可以包含它。 ed 也给我带来了一些问题,所以我回到sed 使用自定义函数来复制不可用的-i 标志以进行就地操作。

    【讨论】:

    • 该死,我已经开始到处使用 heredocs 并且非常依赖 xargs :( 我想我可以从 heredoc 创建一个临时文件并在 xargs 管道中调用它
    • 关于here docs的再说明:标签被搞砸了,不要在here docs中放置标签。
    猜你喜欢
    • 2016-12-27
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 2010-12-08
    • 1970-01-01
    • 2012-08-04
    相关资源
    最近更新 更多