bash tr - ghdrako/doc_snipets GitHub Wiki

tr flags [SET1] [SET2] # characters in SET1 are translated to characters in SET2.

Flags:

  • -c, -C, --complement use the complement of SET1
  • -d, --delete delete characters in SET1, do not translate
  • -s, --squeeze-repeats replace each sequence of a repeated character that is listed in the last specified SET, with a single occurrence of that character
  • -t, --truncate-set1 first truncate SET1 to length of SET2

You can complement the SET1 using -c option. For example, to remove all characters except digits, you can use the following.

$ echo "my username is 432234" | tr -cd [:digit:]
432234

The following command can be used to remove all non-printable characters from a file.

$ tr -cd [:print:] < file.txt

Join all the lines in a file into a single line

The below command will translate all newlines into spaces and make the result as a single line.

$ tr -s '\n' ' ' < file.txt
tr “[:lower:]” “[:upper:]”

tr [:space:] '\t'

To squeeze repeat occurrences of characters specified in a set use the -s option. This removes repeated instances of a character. OR we can say that,you can convert multiple continuous spaces with a single space

echo "Welcome    To    GeeksforGeeks" | tr -s [:space:] ' '
Welcome To GeeksforGeeks

echo "my ID is 73535" | tr -d [:digit:]
my ID is

$ echo "my ID is 73535" | tr -cd [:digit:]  # complement the sets using -c option
73535

tr -cs A-za-z '\n'   # z tekstu generuje kazde slowo w osobnej linii

$ tr -d ",.\!?;:\"\'`" < file # delete file form punctation characters
$ tr -s " " " " < file        # -s removes multiple consecutive occurrences of the same character in the second argument
                              #  multiple spaces in sequence have been replaced with a single space
$ tr '\015' '\012' < file.mac > file.unix  # change the carriage returns at the end of each line in a Macintosh text file into the newline Unix expects 
$ tr -d '\015' < pc.file      #  remove the carriage return from the carriage return/newline pair that a PC file uses as a line terminator
$ tr -cs "[a-z][A-Z]" "[\012*]" # convert consecutive -s non letter chars -c to Unix new line 

Convert to lower case

$ tr 'A-Z' 'a-z' < file 

With Bash≥4, you don't need to tr to convert to upper case since you can use parameter expansions: ${var^^} will expand to the uppercase expansion of var.

#!/bin/bash

# Convert first argument to upper case and save in variable upper1
upper1=${1^^}

# print to console:
printf '%s\n' "$upper1"

# and save to file
printf > file.txt '%s\n' "$upper1"
⚠️ **GitHub.com Fallback** ⚠️