gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:22:59 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com