【问题标题】:Using sed to prepend strings to multiple files使用 sed 将字符串添加到多个文件中
【发布时间】:2013-02-21 11:59:17
【问题描述】:

在过去的一个小时里,我一直在试验 sed,但似乎无法让它发挥作用。我需要在文件夹中所有 python 文件的开头添加一行,例如文件夹“A”。

首先我使用 find 找到所有 python 文件:

find /A -maxdepth 1 -name "*.py"

这显示了 python 文件的列表。 (工作!)

然后,当我按照一些博客和在线教程的建议尝试以下操作时:

find /A -maxdepth 1 -name "*.py" -exec sed -i '1i # -*- coding: utf-8 -*-'

我收到以下错误:

sed: 1: "/A/buttons.py": extra characters at the end of h command

什么是h命令?怎样才能正确地做到这一点?

顺便说一下,我使用的是 Mac OS X。

【问题讨论】:

  • 您要添加的确切行是什么?这对我有用:find A -maxdepth 1 -name "*.py" -exec sed -i '1i Text to prepend' {} \;
  • 我要加:# -*- coding: utf-8 -*-

标签: macos sed


【解决方案1】:

用这个替换你的 find/sed 命令:

find /A -maxdepth 1 -name "*.py" -exec sed -i.bak '1i\
Text to prepend
' {} \;
cd /A
for i in *.py; do
[[ $(sed q $i) != "# -*- coding: utf-8 -*-" ]] && sed -i.bak '1i\
# -*- coding: utf-8 -*-
' $i
done 

【讨论】:

  • 我不想要备份。我希望它直接写入 python 文件。
  • 上述命令只会直接写入您的*.py 文件。为了安全起见,它只会创建额外的*.bak 文件。如果您不想要它,只需删除 .bak
  • Mac OS X 上的终端出现错误:sed: 1: "1i Text to prepend": command i expects \ after text
  • Mac 版本的 sed 确实有其局限性。例如,在i 之后需要\。您可以尝试以下方法:find A -maxdepth 1 -name "*.py" -exec sed -i '1i\<NEWLINE># -*- coding: utf-8 -*-' {} \;
  • 好的,我也试过了......但我得到了这个:sed: 1: "1i\# -*- coding: utf-8 -*-": extra characters after \ at the end of i command 我试图逃避 \ 但它也没有用。怎么回事?
【解决方案2】:

使用下面的命令。它在我的地方工作

find /A -maxdepth 1 -name "*.py"| xargs perl -pi -e 'if($f==1 or $.==1){s/^/# -*- coding: utf-8 -*-\n/g;$f=0;}if(eof){$f=1}'

如果你想在find中使用exec

find /A -maxdepth 1 -name "*.py" -exec perl -pi -e 'if($f==1 or $.==1){s/^/# -*- coding: utf-8 -*-\n/g;$f=0;}if(eof){$f=1}' {}/;

【讨论】:

    猜你喜欢
    • 2013-03-09
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2013-11-27
    • 1970-01-01
    • 2011-05-11
    相关资源
    最近更新 更多