A Bourne shell script that loops through all files

Here's a shell script that you'll find on all the Unix, Linux, and Mac OS X computers I've worked on. The general process of this script is "for every file in the current directory do XYZ".

The specific instance of the shell script shown below says "For every JSP file in the current directory, run the sed script named pp.sed, writing the output to a temporary file, then moving that temporary file back to the original filename".

#!/bin/sh

for i in `ls *.jsp`
do
  echo "Editing $i ..."
  sed -f pp.sed < $i  > $i.tmp
  mv $i.tmp $i
done

This sample shell script actually demonstrates several different shell programming techniques:

  • How to create a for loop in a shell script.
  • How to use the backtick operator to execute the ls *.jsp command inside another command.
  • How to run sed in a mode where it reads a file containing sed commands.

The sed script that I run here modifies a bunch of poorly formatted (but consistent) HTML. Here's the link to that sed script.

Post new comment

The content of this field is kept private and will not be shown publicly.