我在 Ubuntu 平台上,有一个包含许多 .py 文件和子目录(也包含 .py 文件)的目录。我想在每个 .py 文件的顶部添加一行文本。使用 Perl、Python 或 shell 脚本最简单的方法是什么?
最佳答案
find . -name \*.py | xargs sed -i '1a Line of text here'
编辑:根据 tchrist 的评论,处理带空格的文件名。
假设您有 GNU find 和 xargs(因为您在问题上指定了 linux 标签)
find . -name \*.py -print0 | xargs -0 sed -i '1a Line of text here'
如果没有 GNU 工具,你会做类似的事情:
while IFS= read -r filename; do
{ echo "new line"; cat "$filename"; } > tmpfile && mv tmpfile "$filename"
done < <(find . -name \*.py -print)
关于python - 在当前目录和子目录中的每个 Python 文件顶部添加一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7039809/