tr

tr linux command cheatsheet by Thamizhiniyan C S

Introduction

Translate command(tr) can help you in number of ways, ranging from changing character cases in a string to replacing characters in a string.


Syntax

tr [flags] [source]/[find]/[select] [destination]/[replace]/[change]


Important Flags

FlagsDescription

-d

To delete a given set of characters

-t

To concat source set with destination set(destination set comes first; t stands for truncate)

-s

To replace the source set with the destination set(s stands for squeeze)

-c

This is the REVERSE card in this game, for eg. If you specify -c with -d to delete a set of characters then it will delete the rest of the characters leaving the source set which we specified (c stands for complement; as in doing reverse of something)

[:alnum:]

all letters and digits

[:alpha:]

all letters

[:blank:]

all horizontal whitespace

[:cntrl:]

all control characters

[:digit:]

all digits

[:graph:]

all printable characters, not including space

[:lower:]

all lower case letters

[:print:]

all printable characters, including space

[:punct:]

all punctuation characters

[:space:]

all horizontal or vertical whitespace

[:upper:]

all upper case letters

[:xdigit:]

all hexadecimal digits

[=CHAR=]

all characters which are equivalent to CHAR


Examples

CommandsDescription

cat file.txt | tr -s '[a-z]' '[A-Z]'

Convert every alphabetic character to upper case

cat file.txt | tr -s '[:lower:]' '[:upper:]'

Convert every alphabetic character to upper case

cat creds.txt | tr -d '[a-zA-Z: ]'

To view creds of a user which are in digits

tr '()' '[]'

To replace all parentheses ( ) with box brackets [ ]

tr -d a-z

To delete all the lowercase characters a-z

tr -s ' '

To replace all sequences of multiple spaces with just one space

tr [:space:] "\t"

Translates all the white-space characters to tabs

tr -d [:digit:]

To remove all the digits from the string

tr -cd [:digit:]

To remove all characters except digits ( complement )

tr -cs 'i' '0'

Replaces all characters except i with 0 and then squeezes the repeated 0 characters

tr -cs '[:alnum:]' '\n'

To put each word in a new line

tr -s '\n'

To delete the blank lines simply squeeze the repetitive newline characters

echo $PATH | tr ':' '\n'

To print each directory on a separate line from the PATH environment variable

cat .leftShift3 | tr "d-za-cD-ZA-C" "a-zA-Z"

Decrypt the Caesar cipher in the .leftshift3 file

Last updated