How would you insert a copyright message at the very top of every file?
+9
A:
#!/bin/bash
for file in *; do
echo "Copyright" > tempfile;
cat $file >> tempfile;
mv tempfile $file;
done
Recursive solution (finds all .txt
files in all subdirectories):
#!/bin/bash
for file in $(find . -type f -name \*.txt); do
echo "Copyright" > copyright-file.txt;
echo "" >> copyright-file.txt;
cat $file >> copyright-file.txt;
mv copyright-file.txt $file;
done
Use caution; if spaces exist in file names you might get unexpected behaviour.
Paul Creasey
2010-03-15 20:27:50
+1 For his next trick, Paul will be doing it in 5 bytes with `perl -e`
Byron Whitlock
2010-03-15 20:30:21
+1 Nice! Will go into my tools repository. I wonder, how would one make that recursive?
Pekka
2010-03-15 20:30:24
@Byron Whitlock: why perl? sed would do just fine
just somebody
2010-03-15 20:36:17
for recursion, replace `*` with `$(find .)`
Paul Creasey
2010-03-15 20:37:09
2nd version with for loop and find will have problem if files has spaces.
ghostdog74
2010-03-16 00:21:19
A:
You may use this simple script
#!/bin/bash
# Usage: script.sh file
cat copyright.tpl $1 > tmp
mv $1 $1.tmp # optional
mv tmp $1
File list may be managed via find utility
shuvalov
2010-03-15 20:29:48
+4
A:
sed
echo "Copyright" > tempfile
sed -i.bak "1i $(<tempfile)" file*
Or shell
#!/bin/bash
shopt -s nullglob
for file in *; do
if [ -f "$file" ];then
echo "Copyright" > tempfile
cat "$file" >> tempfile;
mv tempfile "$file";
fi
done
to do it recursive, if you have bash 4.0
#!/bin/bash
shopt -s nullglob
shopt -s globstar
for file in /path/**
do
if [ -f "$file" ];then
echo "Copyright" > tempfile
cat "$file" >> tempfile;
mv tempfile "$file";
fi
done
or using find
find /path -type f | while read -r file
do
echo "Copyright" > tempfile
cat "$file" >> tempfile;
mv tempfile "$file";
done
ghostdog74
2010-03-15 23:55:05
very well done. You introduced a lot of techniques here. I will study them later. thank you.
Nadal
2010-03-16 01:41:52