Squoggle
Mac's tech blog
Tag Archives: tr
The tr command
Posted by on April 1, 2020
The tr command:
It’s short for “translate” but might be easier to remember thinking of it as “truncate”. The man page has this to say about it:
DESCRIPTION
Translate, squeeze, and/or delete characters from standard input, writing to standard output.
There are probably books written on what tr can do. I’m just going to leave some notes here on how I typically use it.
The tr program reads from standard input and writes to standard output.
Convert multiple lines of text into a single line of text:
Consider a file named file containing the following data:
abcde fghij klmno pqrst uvwxy
You want to convert the multiple lines into a single line of text. You can do that using tr with something like this:
$ cat file | tr -d '\n'
The result of the command is written to standard output as:
abcdefghijklmnopqrstuvwxy
The -d option deletes. In this case we’re deleting the newline character.
Replace comma with newline:
Sometimes you need to convert a single delimited line to multiple lines. Consider the following file named file containing the following data:
abcde,fghij,klmno,pqrst,uvwxy
We can translate the comma in the file into a new line character with the following command:
$ cat file | tr ',' '\n'
The results look like this:
abcde fghij klmno pqrst uvwxy
Recent Comments