user2533429
user2533429

Reputation: 195

How to loop through many files using perl oneliner

I am trying to add a line to many perl files at line 4 using perl liner. I am using :

 perl -pi -le 'print "     cell_type = pad;" if $. ==4' *.cell.plt

But this is only changing the first file in my directory, not all of them. How do I insert the line in all files at once. I tried several ways but it always fails. Please help. Thanks.

Upvotes: 3

Views: 556

Answers (1)

ikegami
ikegami

Reputation: 385657

You're only reading from one file handle, so there's only one line 4. Fortunately, there is a way of resetting $..

perl -i -ple'
    print "     cell_type = pad;" if $. == 4;
    close ARGV if eof;
' *.cell.plt

(Note that eof is different than eof().)

Alternatively, you can execute perl for each file

find -maxdepth 1 -name '*.cell.plt' -type f -exec \
   perl -i -ple'print "     cell_type = pad;" if $. == 4' {} \;

Upvotes: 7

Related Questions