2011-08-12 23 views

回答

4
#!/usr/bin/perl 

    use Tie::File; 
    for (@ARGV) { 
     tie my @array, 'Tie::File', $_ or die $!; 
     unshift @array, "A new line";   
    } 

要处理目录中的所有.py文件递归地在你的shell中运行以下命令:

find . -name '*.py' | xargs perl script.pl

+1

我更喜欢'perl -pi -e'BEGIN {print“A new line”}'$(find。-name'* .py')':) – hobbs

+0

@hobbs:I得到的想法,但它似乎并没有为我工作(在5.10) –

5
for a in `find . -name '*.py'` ; do cp "$a" "$a.cp" ; echo "Added line" > "$a" ; cat "$a.cp" >> "$a" ; rm "$a.cp" ; done 
+3

在你可能想'RM $ a.cp' – eumiro

+0

@eumiro结束:谢谢。固定。 –

+1

@Didier:你的意思是'发现。 -name * .py'? –

4
import os 
for root, dirs, files in os.walk(directory): 
    for file in files: 
     if file.endswith('.py') 
      file_ptr = open(file, 'r') 
      old_content = file_ptr.read() 
      file_ptr = open(file, 'w') 
      file_ptr.write(your_new_line) 
      file_ptr.write(old_content) 

据我知道你不能在begining或Python文件的末尾插入。只能重写或追加。

+0

+1在Python中做它 –

4

这将

  1. 递归走所有的目录开始与当前工作 目录
  2. 只修改那些文件(胡)的文件名以“的.py”
  3. 结束保存文件的权限(不同于 open(filename,'w')。)

fileinput也给你修改之前备份原始文件的选项。


import fileinput 
import os 
import sys 

for root, dirs, files in os.walk('.'): 
    for line in fileinput.input(
      (os.path.join(root,name) for name in files if name.endswith('.py')), 
      inplace=True, 
      # backup='.bak' # uncomment this if you want backups 
      ): 
     if fileinput.isfirstline(): 
      sys.stdout.write('Add line\n{l}'.format(l=line)) 
     else: 
      sys.stdout.write(line) 
6
find . -name \*.py | xargs sed -i '1a Line of text here' 

编辑:从tchrist的评论,处理文件名用空格。

假设你已经GNU发现和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) 
+1

您获得最短,最明显的方法来接近这个奖。你在目录或文件名中有空白的潜在错误,但是很容易用左侧的'-print0'和右侧的'-0'修复。 – tchrist

+0

@tchrist:它不会仅仅打印STDOUT的答案,而不是将该行添加到每个文件的顶部? –

+0

@David,不,sed的'-i'选项表示就地更新文件。你不会看到任何标准输出。 –

1

什么使用Perl,Python或shell脚本最简单的方法?

我会使用Perl,但那是因为我知道Perl比我知道的Python好得多。哎呀,也许我会在Python中这样做,只是为了更好地学习它。

The 最简单方法是使用您熟悉且可以使用的语言。而且,这也可能是最好的方式。

如果这些都是Python脚本,那么我认为它是Python知识库,或者可以访问一群知道Python的人。所以,你最好在Python中完成这个项目。

但是,也可以使用shell脚本,如果您知道shell最好,请成为我的客人。这里有一个小的,完全未经测试的shell脚本恰好是我的头顶:

find . -type f -name "*.py" | while read file 
do 
    sed 'i\ 
I want to insert this line 
' $file > $file.temp 
    mv $file.temp $file 
done 
+0

+1使用正确的工具'sed',但你有一个错误:当IFS =读-d'\ 0'-r file'时,你应该说'-print0'到'find'并且管道到'以避免有问题的文件名称的问题。 – Sorpigal

+0

实际上,名字中的空格或制表符在这里没什么问题(尽管文件名中间是LF)。看看我的程序,最大的问题是我没有引用变量'$ file'。如果文件名中有空格,我的程序将不起作用。 –

相关问题