背景
我正在寻找剥离任何# TODO
一些Python源代码文件输出的注释git archive
在发送之前。我希望通过一个将从各种 *nix 操作系统运行的脚本来执行此操作,因此它应该尽可能符合 POSIX 标准。
我知道find -print0
and xargs -0
不在基本规范中,但它们似乎很常见,我可以很好地使用它们(除非存在更好的替代方案)。我在用着ed
due to sed -i
不在就地编辑的基本规范中。假设下面的命令是从已解压缩的 git 存档的目录中运行的。
我很高兴有一个整体替代解决方案来剥离# TODO
注释掉,但为了满足我的好奇心,我还想知道我所提出的命令所面临的特定问题的答案。
现有代码
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 注释或以 TODO 开头的行尾注释的整行。
实际结果
(stdout)
,g/^[ \t]*#[ \t]*TODO/d
,s/[ \t]*#[ \t]*TODO//
w
: No such file or directory
当前理论
我相信<< 'EOF'
Heredoc 正在应用于xargs
代替ed
,我不知道如何解决这个问题。
修复<< 'EOF'
Heredoc方向需要一些时间sh -c
最终导致更多问题的诡计,所以我尝试重新解决这个问题,而根本不需要这里文档。
我最终登陆:
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
从技术上讲,不在基本规范中,但是看起来相当便携 https://stackoverflow.com/questions/2792675/how-portable-is-mktemp1所以我很好包括它。ed
也给我带来了一些问题,所以我回到sed
使用自定义函数来复制不可用的-i
就地操作的标志。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)