I want to prepend a text contained in the file disclaimer.txt to all the .m files in a folder.
I tried the following:
text=$(cat ./disclaimer.txt)
for f in ./*.m
do
sed -i '1i $text' $f
done
but it just prepends an empty line.
I want to prepend a text contained in the file disclaimer.txt to all the .m files in a folder.
I tried the following:
text=$(cat ./disclaimer.txt)
for f in ./*.m
do
sed -i '1i $text' $f
done
but it just prepends an empty line.
There are many ways to do this one, but here's a quick first stab:
#!/bin/sh
for file in *.m; do
cat disclaimer.txt $file >> $file.$$
mv $file.$$ $file
done
It concatenates the disclaimer along with the original file into a new temporary file then replaces the original file with the contents of the temporary file.
There are two issues with this:
sed -i '1i $text' $f
First, the variable isn't expanded within single quotes, so sed sees the literal string 1i $text.
The second issue is that the i command expects a following backslash, and the line to be added on a second line, so you'd need to do something like this:
$ text="blah"
$ sed -i $'1i\\\n'"$text"$'\n' "$file"
(in shells with the $'...' expansion, or with literal newlines in shells that don't support it.)
Also, the i command can only add one line, the following lines would be taken as additional sed commands.
Though if you have GNU sed, then just sed -i "1i $text" "$f" should work. But you still only get one line.
For multiple lines, it's probably better to something like what @mjturner showed in their answer.