Well... here are some notes:
1. Using the
ls command to build the list of items in a for loop is not a good idea. The reasons are well explained
here. You can simply use
filename expansion without the ls command, instead:
Code:
for FILE in *.cc *.c
do
:
done
2. In the
if/then statement if you want to test the result of a command the square brackets must be left out:
Code:
if grep -q '#include <stdio.h>' "$FILE"
then
:
fi
Take in mind that the opening square bracket is both a shell built-in and an external command by itself and its behaviour resembles that one of the test command. You can verify by typing the following on the command line and look at the results:
Instead when you test a command you simply put the command after the if keyword. In this case it will return an
exit status that can be 0 (that means success or true) or any other number, usually 1 (that means unsuccessful or false).
3. Using
sed in Linux you don't need to redirect the output to a temporary file, if you want to change the content of the original one. The option
-i let you edit the file in place. Eventually you can add a suffix (near the option) so that a (safe) backup copy of the original file is created using the suffix you specified in the command line, e.g.
Code:
sed -i.bck '1\
#include <stdio.h> ' "$FILE"
Said that, your script might be something like:
Code:
#!/bin/sh
for FILE in *.cc *.c
do
if grep -q printf "$FILE"
if ! grep -q '#include <stdio.h>' "$FILE"
then
sed -i.bck '1i\
#include <stdio.h> ' "$FILE"
fi
fi
done
Note the exclamation point before the command in the if statement: it is the logical
NOT operator. Literally it states:
if the pattern is NOT found in the file, then.... Hope this helps.