I have a Linux folder tree with mixed shell, Perl and Python scripts. None of the scripts have consistent file extensions (.pl, .perl, .py, .sh, or no extension at all). I need to identify which files are Perl scripts, then add a new line of code to set a variable if the variable is not already in the Perl script.
Thanks to How to insert newline character after comma in `),(` with sed? I came up with this code that uses sed to insert the new line of code.
This code works, but is there a more efficient way to do it?
#! /bin/bash
NL='
$|++'
for f in `find "$1" -type f`
do
if [ $(grep -cP "^\#\!/.+/perl" "${f}") -gt 0 ]
then
if [ $(grep -c "$|" "${f}") -eq 0 ]
then
sed -i -r "s/^#!\/(.+)\/perl(.+)$/#!\/\1\/perl\2\\${NL}/g" "${f}"
fi
fi
done
You have a number of Useless Uses of Grep -c there. See http://porkmail.org/era/unix/award.html
The short-circuit
&&is not an optimization, just a personal preference. You could just as well keep your nestedifs, or perhaps something likeIt might be more efficient still to do the first grep (at least) in a
sedscript since presumably you are only interested in the first line of the script. (On the other hand, why do you have a/gflag on thesedsubstitution if that is the case?)Actually you probably mean