python - 在当前目录和子目录中的每个 Python 文件顶部添加一行

标签 python linux perl shell

我在 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/

相关文章:

python - 让 python 和 meteor 说话的最佳方式

regex - 在 Perl 中的两个符号之间找不到模式时如何删除模式?

linux - 内部调用 Linux 命令并将输出保存到文件的 Perl 脚本?

python - 如何获取 numpy 数组中不连续索引的元素?

python - Django:如何获取外键ID?

linux - 在 Linux 中保存钩子(Hook)文件

c++ - Any Time 函数保证调用返回不同的值

linux - 使用命令行输入参数

python - 相当于 perl "a"的 python 是什么。 ."azc"

python - 为什么我不能在 python 中重写这个方法?