If you completed the steps in the previous section, you might have noticed that you did a lot of typing. And, goodness, if you made it through steps 3 and 5, your fingers are probably on strike right about now. If you plan to encode or decode with ROT13 frequently, consider embedding the sed commands in a shell script to avoid retyping them each time you encode or decode text, as shown in Figure 17.4. You might refer back to Chapter 10 for details on shell scripts before you get started here.
1. | vi rot13 Start a new shell script to process your commands. |
2. | |
3. | /bin/sed y/abcdefghijklmnopqrstuvwxy
→ zABCDEFGHIJKLMNOPQRSTUVWXYZ/nopqr
→ stuvwxyzabcdefghijklmNOPQRSTUVWXY
→ ZABCDEFGHIJKLM/
Specify the sed program (using the full path to make the program a little more flexible) and the command that encodes and decodes ROT13 text. It’s better to make the shell script self-contained, so instead of referencing an external file with the sed script, we’ll just put it in the command line here. |
4. | /bin/sed y/abcdefghijklmnopqrstuvwxy
→ zABCDEFGHIJKLMNOPQRSTUVWXYZ/nopqr
→ stuvwxyzabcdefghijklmNOPQRSTUVWXY
→ ZABCDEFGHIJKLM/ "$1"
Here, we added $1 to pass the filename from the command line (as in rot13 thisfile) to sed. |
5. | /bin/sed y/abcdefghijklmnopqrstuvwxy
→ zABCDEFGHIJKLMNOPQRSTUVWXYZ/nopqr
→ stuvwxyzabcdefghijklmNOPQRSTUVWXY
→ ZABCDEFGHIJKLM/ "$1" | more
Next, pipe the output to more so you see the file one screen at a time. |
6. | Save and exit out of the file. |
7. | chmod u+x rot13
Make the shell script executable, so you can just enter the name rot13 rather than sh rot13. |
8. | ./rot13 limerick
Test the script. Because we developed this script in a directory that’s not in the path, we have to execute the script with ./rot13. If you develop the script in a directory in your path, you should just be able to type rot13. |
✓ Tip
You can also build in an option to redirect the output of the script to a file and save it for later. Basically, all you do is create an if-then statement and give yourself the option of automatically redirecting the output to a filename, as Code Listing 17.7 shows. Check out Chapter 10 for more information about scripts and if-then statements.
[ejr@hobbes creative]$ more rot13
#! /bin/sh
# If the first item (after the script name) on the command
# line is save or s, and the second item is a readable file
# then do the first case.
if [ ( "$1" = "save" -o "$1" = "s" ) -a ( -r "$2" ) ]
then
# This case saves the ROT13 output under the same filename with
# a rot13 extension.
/bin/sed
y/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/nopqrstuvwxyzabcdefghijklmNOPQRST
→ UVWXYZABCDEFGHIJKLM/ "$2" > "$2.rot13"
else
# This case pipes the ROT13 output to more, because a save
# wasn't specified.
/bin/sed
y/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/nopqrstuvwxyzabcdefghijklmNOPQRST
→ UVWXYZABCDEFGHIJKLM/ "$1" | more
fi
[ejr@hobbes creative]$
|