2011-08-12 20 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'。如果文件名中有空格,我的程序將不起作用。 –

相關問題