Insert copyright message into multiple files

2019-03-27 06:10发布

问题:

How would you insert a copyright message at the very top of every file?

回答1:

#!/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.



回答2:

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


回答3:

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



回答4:

Working in Mac OSX:

#!/usr/bin/env bash

for f in `find . -iname "*.ts"`; do # just for *.ts files
  echo -e "/*\n * My Company \n *\n * Copyright © 2018 MyCompany. All rights reserved.\n *\n *\n */" > tmpfile
  cat $f >> tmpfile
  mv tmpfile $f
done