45.35 Using a Control Character in a ScriptThere are times when you need to use non-printing control characters in a script file. If you type them directly into the file, they can be invisible to printers and on your screen - or, worse, they can cause trouble when you print or display the file. One time you might need to store control characters in a script is when you're writing sed substitution commands; you don't know what delimiters to use because the strings you're substituting could contain almost any text:
sed "s/$something/$whoknows/"
Because
sed
can use almost any character as the delimiter (
34.7
)
,
you can
use a control character like CTRL-a instead of the slash ( The answer is to use a command that will create the control characters as the script runs - and store them in shell variables. 45.35.1 With echo
If
your version of
echo
(
8.6
,
46.10
)
interprets an octal number in a
string like
45.35.2 With tr and echoIf your echo can't make control characters directly, the tr utility can do it for you. tr understands octal sequences, too. Make your echo output characters you don't want, and have tr translate them into the control characters you do want. For example, to make the 4-character sequence ESCape CTRL-a [ CTRL-w , use a command like this:
escseq=`echo 'ea[w' | tr 'eaw' '\033\001\027'` tr reads the four characters down the pipe from echo ; it translates the e into ESCape (octal 033), the a into CTRL-a (octal 001), and the w into CTRL-w (octal 027). The left bracket isn't changed; tr prints it as is. The script.tidy script in article 51.6 shows a way to set several control characters in several shell variables with one command - that's efficient because it cuts the number of subprocesses needed. Another way to get control characters is with the handy jot ( 45.11 ) command on the CD-ROM. - |
|