I have a directory with a huge number of files. I want to write a bash script to -

  1. Enter that directory
  2. Find out which of them are Perl scripts (but none of them have a .pl extension)
  3. Add a line at the top of each of the line (I intend to add a new shebang) If not a Perl script, do nothing

I am unable to search for the Perl scripts, tried using grep but not getting the proper command. Also, the third step is also where I am stuck.

  • No way to do your point 3. You can see this post, unix.stackexchange.com/questions/87772/…, and in particular Gilles' answer which states: There is no way to insert data at the beginning of a file, all you can do is create a new file, write the additional data, and append the old data. So you'll have to rewrite the whole file at least once to insert the first line. – MariusMatutiae Apr 15 '16 at 10:45
  • Okay, but is it possible the replace the text on the first line with something else? – Suraj Bhatia Apr 15 '16 at 11:10

The most you can do to find the perl files is to use perl itself to judge. perl -c returns non-zero exit code if the file is not a correct perl code which is definitely true for MOST files that are not perl at all. Unfortunately, it does the same when it's fed with faulty perl code and returns 0 when the the file is actually not a perl code but can be parsed without error as if it were. If you can live with that risk, the core of it may be this:

for FILE in * ; do
   if perl -c "$FILE" >/dev/null ; then
      sed -i -e '1i#!/usr/bin/perl' "$FILE"

Remark: once I touch the files anyway, I would add .pl extension, unless there is some REALLY serious reason to be blind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.