tr (Replace Characters)

The tr
(TRanslate) command is used to replace a string with another string. As the command doesn't have a file input argument, it is often used with the pipe or redirection.
tr command syntax
The tr
command syntax itself is tr ["original string"]["new string"]
. The original and new strings should be quoted with " " or ' '; however, the command doesn't work on its own as it needs standard input.
tr command with pipe
To make an input to the tr
command, you can use the cat
command and connect it with the tr
command.
To demonstrate the command, we use a customer purchase data set example below. The file name is purchase.txt and its data fields are, from left to right:
- Customer ID
- First name
- Last name
- Product name
- Purchase unit
- Purchase value
Using this data set, if you want to change the delimiter (a symbol that separates strings) from ,
(comma) to a space, run the following command.
You can see the following result in your command line.
As the standard output is still the command line, you cannot save the result. To save it in a file, run the command below.
In the purchase_s.txt file, you'll see the same result as the one in the command line.
tr command with standard input redirection
For the same data set, you can also use standard input redirection to make an input to the tr
command as shown below.
If you want to save the result, you can run the command below.