Table of Contents
Introduction
In this tutorial, we will explore the tr
command in Linux, a versatile utility in Linux for translating or deleting characters in text. The tr
command is primarily used for character-level transformations, making it an essential tool for modifying the contents of text files or input streams. By specifying certain rules, tr
allows you to replace or remove specific characters efficiently. Let’s dive into practical examples to see the using tr
command in Linux.
What is the purpose of the tr
command?
The
tr
command, short for “translate,” is a powerful utility in Linux used to translate or delete characters in text data. It performs specific transformations on the contents of a file or data from a standard input, based on rules defined by the user.
tr command syntax
tr [OPTION]... [INPUT [OUTPUT]]
According to the man page, it is described as follows.
- tr – translate or delete characters.
- man tr – More details information about tr command.
tr command in Linux with an example
I have created a file tr_command.txt as below
[vagrant@DevopsRoles ~]$ cat tr_command.txt HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x. Devops Roles. Devops Roles. Devops Roles. Devops Roles. Hello world :)
How to convert small letters into capital letters.
[vagrant@DevopsRoles ~]$ cat tr_command.txt | tr [:lower:] [:upper:] HUUPV, MY WEBSITE DEVOPSROLES.COM AND HUUPHAN.COM.SN:199X. DEVOPS ROLES. DEVOPS ROLES. DEVOPS ROLES. DEVOPS ROLES. HELLO WORLD :)
The following command is used to convert each space of the text by a newline (\n)
[vagrant@DevopsRoles ~]$ cat tr_command.txt | tr [:space:] '\n' HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x. Devops Roles. Devops Roles. Devops Roles. Devops Roles. Hello world :)
uses –s option for searching and replacing any string from a text
[vagrant@DevopsRoles ~]$ cat tr_command.txt | tr -s ' ' '\t' HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:199x. Devops Roles. Devops Roles. Devops Roles. Devops Roles. Hello world :)
Delete numbers
[vagrant@DevopsRoles ~]$ cat tr_command.txt | tr -d "[:digit:]" HuuPV, My website DevopsRoles.com and HuuPhan.com.SN:x. Devops Roles. Devops Roles. Devops Roles. Devops Roles. Hello world :)
Output the converted output to a file
[vagrant@DevopsRoles ~]$ cat tr_command.txt | tr "[:upper:]" "[:lower:]" > result_tr.txt
Conclusion
The tr
command is a straightforward yet powerful tool in Linux, used to translate or delete characters in text. For more detailed information and to explore additional options that may vary by Linux distribution, you can consult the manual page for the tr
command by typing man tr
in the terminal. Thank you for visiting the DevopsRoles page!