Linux Batch Prepend Header File to Series of Files

Submitted by nigel on Thursday 30th September 2010

Have you ever been in a position where you need to prepend a header file to a series of other files? Typically, if you have created a series of program files and needed to add a standard copyright notice at the top of every file in the suite, then this would be the case.

Below is a method of achieving exactly this. We are going to use the UNIX tac command line utility (cat backwards!) to achieve this, and use a shell script for statement to loop though each file in the directory.

The basic syntax will be:

tac program_file prepend_file | tac > new_file

Now for my example, I have two areas within my bookcat Drupal module directory structure containing my source files - includes/templates and includes/classes. I will copy the entire directory tree to a temporary area, then run the script below which will add the necessary headers.

#!/bin/sh
 
# Script to prepend standard header file to .php and .inc PHP language files 
 
# Temp directory 
tempdir=/usr/local/bookcat/bookcat-temp
# Final directory
finaldir=/usr/local/bookcat/bookcat-6.x-1.0-alpha1
# Header to be used to prepend
header=/usr/local/bookcat/header
 
 
 
# Template files first
cd "$tempdir"/includes/templates
for k in `ls *.inc *.php`
do
    tac $k $header | tac > "$finaldir"/includes/templates/"$k"
done
 
 
# Classes next
cd "$tempdir"/includes/classes
for k in `ls *.inc`
do
    tac $k $header | tac > "$finaldir"/includes/classes/"$k"
done
Always good when a 10 minute job takes only 10 minutes!
blog terms
Linux