Using SED for Variable Replacement

I was writing a KSH script with the following snippet:

exercises="ex1 ex2 ex3"
for exercise in exercises; do
    mkdir $home/$exercise
    filename=Target${exercise}Config.xml
done

The problem was I did not want the file to be named Targetex1Config.xml, but TargetExercise1Config.xml, respectively.  So, I wondered if it was possible to do double-dereferencing (i.e., go from exercise to ex1 to Exercise1, such as in the following:

exercises="ex1 ex2 ex3"
ex1=Exercise1
ex2=Exercise2
ex3=Exercise3
for exercise in exercises; do
    mkdir $home/$exercise
    filename=Target${${exercise}}Config.xml
done

That did not work, but a friend showed me the following use of SED with a regular expression to do the replacement:

exercises="ex1 ex2 ex3"
for exercise in exercises; do
    mkdir $home/$exercise
    newName=`echo $exercise | sed -e s/ex/Exercise/`
    filename=Target${newName}Config.xml
done

This worked like a charm (at least once I figured out that the ‘`’ above is not an apostrophe but the backward apostrophe underneath the ‘~’ key).  Later that day when I needed to copy and rename a bunch of files using a boring, repetitive pattern, I used SED to help make that easier:

for file in Provider*.xml ; do 
  mv $file `echo $file | sed 's/Ex/Exercise/'` ; 
done

I would like to have used Ruby to modify the contents of the files automatically using regular expressions, but Ruby is not available in this environment, and case-sensitivity in changes is an issue. Perhaps AWK can help me out with this. Either way, I plan to dig deeper into SED and AWK.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s