I’m trying to replace some annotations in ‘jsp’ pages via a bash script.
My issue is that, randomly, some files are wiped while others have the header properly replaced.
The script:
echo "Processed Files:" > processedFiles.txt
for f in $(find . -name "*.jsp")
do
#Check if the file contains the doctype
htmlPage=`cat $f | grep "<!DOCTYPE HTML PUBLIC \"-\/\/W3C\/\/DTD HTML 4.0 Strict\/\/EN\">"`
oldHtmlPage=`cat $f | grep "<!DOCTYPE HTML PUBLIC \"-\/\/W3C\/\/DTD HTML 3.2\/\/EN\">"`
if [ ${#htmlPage} -gt 0 ] || [ ${#oldHtmlPage} -gt 0 ]
then
echo processing $f
# if read only, allow us to write on it
rdonly=0
if [ ! -w "$f" ]
then
chmod +w "$f"
rdonly=1
fi
# replace headers
if [ ${#htmlPage} -gt 0 ]
then
cat "$f" | sed 's/<!DOCTYPE HTML PUBLIC "-\/\/W3C\/\/DTD HTML 4.0 Strict\/\/EN">/<!DOCTYPE html>/g' > "$f"
fi
if [ ${#oldHtmlPage} -gt 0 ]
then
cat "$f" | sed 's/<!DOCTYPE HTML PUBLIC "-\/\/W3C\/\/DTD HTML 3.2\/\/EN\">/ /g' > "$f"
fi
# add file to list of processed
echo $f'\n' >> processedFiles.txt
# restore read only
if [ $rdonly -eq 1 ]
then
chmod -w $f
fi
else
# jsp without html doctype declaration
echo ignoring $f
fi
done
When executing the sed command in some cases the content is properly replaced, but in others the full content is wiped, so the file to which I’m injecting the code becomes empty.
I assume that, due to the if condition, only files that contain the header to be replaced go into that logic path, and I saw no differences between the wiped files and the files that behaved as expected.
I assume that if a file would not match the sed expression the file would remain untouched (in any case the wiped files seem to contain that header)
Any idea on what may the issue be would be greatly appreciated 🙂
This little snippet:
is not really a good idea (reading and writing to the same file at the same time). It’s possible that the writing of data to the file will interfere with the reading.
It’s probably safer to use
sed -i(in-place editing).If your
seddoesn’t have in-place editing, find one that does. Or use something like:And, please, if you value your sanity, make backups of the entire directory tree before you run these sort of scripts.