There's no simple answer to this. Each operation really needs to be addressed separately, and some tools are better suited to certain operations than others. Changing all of one character to another, for example, or deleting them, is really best done with tr
, although sed
is capable of it.
Xerox's example above covers the basic substitution feature of sed
, but there are a couple of weaknesses with it I need to address.
First, Useless Use Of Cat
can (and should) read files directly.
Second, the quoting. He's attempted to let the shell variables expand by unquoting them in the expression. This isn't safe. The usual way to handle it is to simple double-quote the whole string.
To explain in more detail, you should never leave the quotes off a parameter expansion unless you explicitly want the resulting string to be word-split by the shell (globbing patterns are also expanded). This is a vitally important concept in scripting, so train yourself to do it correctly now. You can learn about the exceptions later.
Third, you can apply multiple expressions at once using the -e
option, and you can edit a file in place with the -i
option (and optionally save the original to a backup file), so you don't need a temp file.
sed -i.bckp -e "s/$a/$b/g" -e "s/$c//g" letter.txt
Here are a few useful sed references:
Here are a few useful awk references:
For other tools like tr
, start by calling up "info coreutils". There are also info pages for grep
are a core function of many of these tools and others, and learning them is one of the best bang-for-the-buck uses you can put your study time to.
Here are a few regular expressions tutorials:
Finally, you might consider using ed
for some of this. As a real, and very light, universally available, text editor, it's a good choice for scripting out simple edits, such as deleting lines or moving them around.
How to use ed:
(also read the info page)