Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add line on top of each Python file in current and sub directories

I'm on an Ubuntu platform and have a directory containing many .py files and subdirectories (also containing .py files). I would like to add a line of text to the top of each .py file. What's the easiest way to do that using Perl, Python, or shell script?

like image 807
MartinC Avatar asked Aug 12 '11 12:08

MartinC


3 Answers

find . -name \*.py | xargs sed -i '1a Line of text here'

Edit: from tchrist's comment, handle filenames with spaces.

Assuming you have GNU find and xargs (as you specified the linux tag on the question)

find . -name \*.py -print0 | xargs -0 sed -i '1a Line of text here'

Without GNU tools, you'd do something like:

while IFS= read -r filename; do
  { echo "new line"; cat "$filename"; } > tmpfile && mv tmpfile "$filename"
done < <(find . -name \*.py -print)
like image 149
glenn jackman Avatar answered Nov 15 '22 19:11

glenn jackman


for a in `find . -name '*.py'` ; do cp "$a" "$a.cp" ; echo "Added line" > "$a" ; cat "$a.cp" >> "$a" ; rm "$a.cp" ; done
like image 28
Didier Trosset Avatar answered Nov 15 '22 20:11

Didier Trosset


    #!/usr/bin/perl

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

To process all .py files in a directory recursively run this command in your shell:

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

like image 36
Eugene Yarmash Avatar answered Nov 15 '22 19:11

Eugene Yarmash