Reputation: 13
I have a simple Bash shell Script to loop through each file in a directory and check is the copyright message is at the top of the file. If it's not there is should add it.
The script is giving an error when I try to use a variable in the sed command. I have looked at other similar questions and tried double quotes "", I have tried using a different operator but still can't find the solution. Can someone possibly point out what I am doing wrong?
Msg='/*------------------------------------------------------------------------------
*******************************************************************************
* Copyright message here
*******************************************************************************
*----------------------------------------------------------------------------*/'
for file in *
do
if grep -Fxq "$Msg" $file
then
echo Marvel Message already exist: $file
else
if test -f "$file"
then
echo "Adding Message to file: $file"
sed -i "1s/^/${Msg}\n/" $file
fi
fi
done
Upvotes: 1
Views: 408
Reputation: 5591
Simply you can do it with marge like this, here with echo "$Msg" > tmp.txt
you are creating a file with your $Msg
as header of the tmp file. And with cat $file >> tmp.txt
you are merging the file.
for file in *
do
if grep -Fxq "$Msg" "$file"
then
echo Marvel Message already exist: "$file"
else
if test -f "$file"
then
echo "Adding Message to file: $file"
#sed -i "1s/^/${Msg}\n/" $file
echo "$Msg" > tmp.txt
cat "$file" >> tmp.txt
mv tmp.txt "$file"
fi
fi
done
Hope this will help you.
Upvotes: 0
Reputation: 247210
I would not use sed for this. I would use ed:
ed "$file" <<END
1i
$Msg
.
wq
END
Or, using sponge
from the moreutils package
{ echo "$Msg"; cat "$file"; } | sponge "$file"
Upvotes: 2