Hi,
Below is a simple script that I've just completed, and I would be grateful
if someone could point out any potential problems with the techniques used.
This is my first real script and I'd rather not develop bad habits!
The idea is to use it like a filter. I want it to take a csv file at stdin
and a specified file form the argument list of one, and direct the final
output to stdout for maybe further processing or directing straight to a
file. The output will have the place-holders replaced with the replacement
text sourced from csv file.
The csv file contains two fields (not quoted).
Field1 is a place-holder name (E.g. 10, 989, blah)
Field2 is the replacement text which will not contain the | char used in the
sed line (E.g. hello !10! !blah!)
A typical csv line might look like:
10,Smelly bloke
The specified file may contain many lines like:
Hello !10!
Yo !10!.
The output of the script using these will be:
Hello Smelly bloke
Yo Smelly bloke
The script works exactly as required (whoo hoo!), but that could be due to
good fortune and circumstances rather than doing it right.
Thanks for any comments/observations.
---
#!/bin/bash
# if the specified file doesn't exist, bomb out with a file missing message,
otherwise continue with main processing
if [ -f $1 ]; then
cp $1 w # set initial work file to contents of specified file
while read foo <&0 # loop for each line of stdin
do
holder=!`echo $foo | cut -d , -f 1`! # get place-holder name
text=`echo $foo | cut -d , -f 2-` # get replacement text
sed "s|$holder|$text|g" w > y # replace all entries
cp y w # update work file with new version
done
cat w # send results to stdout
rm w y #remove work files
else
echo "file $1 missing"
fi