Small shell tools for text editing

Slashdot it! Delicious Share on Facebook Tweet! Digg!

Substituting and Deleting Characters

Using the tr command, you can substitute or delete (single) characters in a pipe. You delete using the -d option. You can also replace consecutive identical characters with just one using -s . Character classes can also be used. As with sed , you can set search and replace patterns through character ranges in the form [CHAR1-CHAR2] . The substitution is one to one, but you can have one substitution for multiple searches and vice versa.

Special characters are escaped with \ for evaluation. Most often, you would use the form feed (\f ), new line (\n ), or horizontal tab escape (\t ) sequence. The manual also includes further options.

The examples in Figure 7 show the following action:

Figure 7: Different uses of the tr tool.
  • Substitution of tabs with the | symbol.
  • Replacement of all characters with uppercase.
  • Replacement of all u characters with their German umlaut equivalents.
  • Character deletion

You can set the search and replace entries as variables. Listing 2 shows a short shell script that uses variables instead of fixed patterns.

Listing 2

Script Using tr

01 #! /bin/sh
02 echo -n "  Search: ";read search_term
03 echo -n "Replace with: ";read erbe
04 cat a.txt | tr "$search_term" "$erbe"

Octal Format

You can use od to dump a file or output of a pipe into octal or some other format. The program can help track down (not always reproducible) special characters. Without options, the output is in octal bytes.

Using the -c option, the output extracts into ASCII, with special and control characters indicated. Using -x , it shows the information in hexadecimal.

Buy this article as PDF

Express-Checkout as PDF

Pages: 1

Price $0.99
(incl. VAT)

Buy Ubuntu User

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content