views:

144

answers:

3

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
+1 For his next trick, Paul will be doing it in 5 bytes with `perl -e`
Byron Whitlock
+1 Nice! Will go into my tools repository. I wonder, how would one make that recursive?
Pekka
@Byron Whitlock: why perl? sed would do just fine
just somebody
for recursion, replace `*` with `$(find .)`
Paul Creasey
2nd version with for loop and find will have problem if files has spaces.
ghostdog74
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
+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
very well done. You introduced a lot of techniques here. I will study them later. thank you.
Nadal