TR(1POSIX)

TR(1POSIX) ๐Ÿ’…

POSIX Programmer's Manual ๐ŸŽ€ โ€” okay bestie, this is the POSIX page, not the Linux one. Keep that energy. โœจ


PROLOG ๐ŸŒธ

This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. ๐Ÿ’€

So like, Linux might do its own thing. Check the matching Linux page, or it might not even exist there. Periodt.

NAME โœจ

tr โ€” translate characters ๐Ÿฆ‹

SYNOPSIS ๐Ÿ’–

tr [-c|-C] [-s] string1 string2

tr -s [-c|-C] string1

tr -d [-c|-C] string1

tr -ds [-c|-C] string1 string2

DESCRIPTION ๐Ÿ‘‘

The tr utility shall copy the standard input to the standard output with substitution or deletion of selected characters. The options specified and the string1 and string2 operands shall control translations that occur while copying characters and single-character collating elements. ๐Ÿ’ซ

OPTIONS ๐ŸŽ€

The tr utility shall conform to the Base Definitions volume of POSIX.1โ€2017, Section 12.2, Utility Syntax Guidelines. No cap.

The following options shall be supported:

  • -c โ€” Complement the set of values specified by string1. See the EXTENDED DESCRIPTION section.
  • -C โ€” Complement the set of characters specified by string1. See the EXTENDED DESCRIPTION section.
  • -d โ€” Delete all occurrences of input characters that are specified by string1.
  • -s โ€” Replace instances of repeated characters with a single character, as described in the EXTENDED DESCRIPTION section.

OPERANDS ๐Ÿ“

The following operands shall be supported:

  • string1, string2 โ€” Translation control strings. Each string shall represent a set of characters to be converted into an array of characters used for the translation. For a detailed description of how the strings are interpreted, see the EXTENDED DESCRIPTION section.

STDIN ๐ŸŒˆ

The standard input can be any type of file.

INPUT FILES ๐ŸŒฟ

None.

ENVIRONMENT VARIABLES ๐Ÿ’–

The following environment variables shall affect the execution of tr:

  • LANG โ€” Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of POSIX.1โ€2017, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
  • LC_ALL โ€” If set to a non-empty string value, override the values of all the other internationalization variables.
  • LC_COLLATE โ€” Determine the locale for the behavior of range expressions and equivalence classes.
  • LC_CTYPE โ€” Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments) and the behavior of character classes.
  • LC_MESSAGES โ€” Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
  • NLSPATH โ€” Determine the location of message catalogs for the processing of LC_MESSAGES.

ASYNCHRONOUS EVENTS ๐Ÿฆ‹

Default.

STDOUT โœจ

The tr output shall be identical to the input, with the exception of the specified transformations.

STDERR ๐Ÿ˜ญ

The standard error shall be used only for diagnostic messages.

OUTPUT FILES ๐Ÿ’…

None.

โœจ EXTENDED DESCRIPTION โœจ

okay so this is the part where it gets juicy ๐Ÿ’– the two operands string1 and string2 (when string2 is actually there) define two arrays of characters, and everything below is the toolkit for putting characters โ€” or single-character collating elements โ€” into those arrays. one lil heads-up before we dive in: if any of these constructs end up producing multi-character collating elements, tr is gonna quietly exclude them from the resulting array. like, no diagnostic, no text, no nothing. just gone. ๐Ÿซฅ

  • character โ€” literally any character that isn't described by one of the conventions below just represents itself. simple as that, bestie.
  • \octal โ€” octal sequences are how you represent characters by their specific coded values. an octal sequence is a <backslash> followed by the longest sequence of one, two, or three octal-digit characters (01234567). it takes the value whose encoding is represented by that one-, two-, or three-digit octal integer and drops it into the array. for multi-byte characters you need multiple concatenated escape sequences of this type โ€” and yes, that means including the leading <backslash> for each byte. every single one. ๐Ÿงš
  • \character โ€” the <backslash>-escape sequences listed in the Base Definitions volume of POSIX.1โ€2017, Table 5-1, Escape Sequences and Associated Actions are supported: '\\', '\a', '\b', '\f', '\n', '\r', '\t', '\v'. that's the whole squad. and if you use any other character after the <backslash> โ€” anything that isn't an octal digit โ€” the results are unspecified ๐Ÿ’€. also, if there's no character at all after the <backslash>? also unspecified. so don't.
  • c-c โ€” in the POSIX locale, this is the range of collating elements between the two range endpoints, inclusive, as defined by the collation sequence โ€” as long as neither endpoint is an octal sequence of the form \octal. the characters or collating elements in the range get placed into the array in ascending collation sequence. if the second endpoint comes before the starting endpoint in the collation sequence, it's unspecified whether the range is just empty or whether the whole construct is treated as invalid ๐Ÿ™ˆ. and in locales that aren't the POSIX locale, this construct has unspecified behavior. periodt.

but โ€” plot twist โ€” if either or both of the range endpoints are octal sequences of the form \octal, then this represents the range of specific coded values between the two endpoints, inclusive. iconic little exception ๐Ÿ’…

  • [:class:] โ€” represents all characters belonging to the defined character class, as defined by the current setting of the LC_CTYPE locale category. these are the class names that shall be accepted when specified in string1:
alnum   blank   digit   lower   punct   upper
alpha   cntrl   graph   print   space   xdigit

plus, character class expressions of the form [:name:] shall be recognized in those locales where the name keyword has been given a charclass definition in the LC_CTYPE category. so it's giving extensible, we love to see it ๐ŸŒˆ

when both -d and -s are specified, any of the character class names shall be accepted in string2. otherwise? only the character class names lower or upper are valid in string2, and then only if the corresponding character class (upper and lower, respectively) is specified in the same relative position in string1. such a specification is interpreted as a request for case conversion ๐Ÿ‘‘

when [:lower:] appears in string1 and [:upper:] appears in string2, the arrays shall contain the characters from the toupper mapping in the LC_CTYPE category of the current locale. when [:upper:] appears in string1 and [:lower:] appears in string2, the arrays shall contain the characters from the tolower mapping in the LC_CTYPE category of the current locale. the first character from each mapping pair goes in the array for string1, and the second character from each mapping pair goes in the array for string2, in the same relative position. matching sets, bestie ๐Ÿซถ

except for case conversion, the characters specified by a character class expression get placed into the array in an unspecified order โ€” so like, don't build your whole personality around their order, okay?

and if the name you specified for class doesn't define a valid character class in the current locale, the behavior is undefined. not "kinda weird", not "maybe fine" โ€” undefined. ๐Ÿ’€
  • [=equiv=] โ€” represents all characters or collating elements belonging to the same equivalence class as equiv, as defined by the current setting of the LC_COLLATE locale category. an equivalence class expression is only allowed in string1, or in string2 when it's being used by the combined -d and -s options. the characters belonging to the equivalence class go into the array in an unspecified order.
  • [x*n] โ€” represents n repeated occurrences of the character x. because this expression is used to map multiple characters to one, it's only valid when it occurs in string2. if n is omitted or is zero, it's interpreted as large enough to extend the string2-based sequence to the length of the string1-based sequence. if n has a leading zero, it's interpreted as an octal value. otherwise, it's interpreted as a decimal value. ๐ŸŒธ

now, when the -d option is not specified:

  • if string2 is present, each input character found in the array specified by string1 shall be replaced by the character in the same relative position in the array specified by string2. but โ€” and this is the messy part โ€” if the array specified by string2 is shorter than the one specified by string1, or if a character occurs more than once in string1, the results are unspecified. no cap ๐Ÿ˜ญ
  • if the -C option is specified, the complements of the characters specified by string1 โ€” that's the set of all characters in the current character set, as defined by the current setting of LC_CTYPE, except for those actually specified in the string1 operand โ€” shall be placed in the array in ascending collation sequence, as defined by the current setting of LC_COLLATE.
  • if the -c option is specified, the complement of the values specified by string1 shall be placed in the array in ascending order by binary value. (different vibe from -C, iykyk ๐Ÿ‘€)
  • and because the order in which characters specified by character class expressions or equivalence class expressions appear is undefined, such expressions should only be used if the intent is to map several characters into one. the one exception is case conversion, as described previously. ๐Ÿ’…

when the -d option is specified:

  • input characters found in the array specified by string1 shall be deleted. poof. gone. โœจ
  • when the -C option is specified with -d, all characters except those specified by string1 shall be deleted. the contents of string2 are ignored, unless the -s option is also specified.
  • when the -c option is specified with -d, all values except those specified by string1 shall be deleted. the contents of string2 shall be ignored, unless the -s option is also specified.
  • the same string cannot be used for both the -d and the -s option. when both options are specified, you need both string1 (used for deletion) and string2 (used for squeezing). required. both. no shortcuts ๐Ÿšจ

when the -s option is specified, after any deletions or translations have taken place, repeated sequences of the same character shall be replaced by one occurrence of the same character โ€” if that character is found in the array specified by the last operand. if the last operand contains a character class, like in this lil example:

tr -s '[:space:]'

then the last operand's array shall contain all of the characters in that character class. however, in a case conversion (as described previously), like this one:

tr -s '[:upper:]' '[:lower:]'

the last operand's array shall contain only those characters defined as the second characters in each of the toupper or tolower character pairs, as appropriate. slay, but specific ๐Ÿ’œ

and finally: an empty string used for string1 or string2 produces undefined results. don't do it. i'm begging. ๐Ÿ™

โœจ EXIT STATUS โœจ

the following exit values shall be returned:

  • 0 โ€” all input was processed successfully. we ate. ๐ŸŽ€
  • >0 โ€” an error occurred. ๐Ÿ’€

โœจ CONSEQUENCES OF ERRORS โœจ

Default.

the following sections are informative.


โœจ APPLICATION USAGE โœจ

  • if necessary, string1 and string2 can be quoted to avoid pattern matching by the shell. protect your strings, bestie ๐Ÿซถ
  • if an ordinary digit (one that's representing itself) is going to follow an octal sequence, the octal sequence must use the full three digits to avoid ambiguity. all three. no skimping. โญ
  • when string2 is shorter than string1, there's a difference between historical System V and BSD systems. a BSD system pads string2 with the last character found in string2. so it's possible to do this:
tr 0123456789 d

which would translate all digits to the letter 'd'. but since this area is specifically unspecified in this volume of POSIX.1โ€2017, both the BSD and System V behaviors are allowed โ€” and a conforming application cannot rely on the BSD behavior. so it would have to code the example like this instead:

tr 0123456789 '[d*]'

see the difference? yeah. that's the safe one. ๐Ÿ’…

  • it should be noted that, despite similarities in appearance, the string operands used by tr are not regular expressions. i know they look like it. they are not. do not come for me. ๐Ÿ™ˆ
  • unlike some historical implementations, this definition of the tr utility correctly processes NUL characters in its input stream. and you can strip NUL characters by using:
tr -d '\000'

iconic behavior, honestly ๐Ÿ‘‘


โœจ EXAMPLES โœจ

  1. the following example creates a list of all words in file1, one per line in file2, where a word is taken to be a maximal string of letters.
tr -cs "[:alpha:]" "[\n*]" <file1 >file2
  1. the next example translates all lowercase characters in file1 to uppercase and writes the results to standard output.
tr "[:lower:]" "[:upper:]" <file1
  1. this example uses an equivalence class to identify accented variants of the base character 'e' in file1, which are stripped of diacritical marks and written to file2.
tr "[=e=]" "[e*]" <file1 >file2

๐Ÿ’ญ RATIONALE ๐Ÿ’ญ

okay so bestie, gather round for some iconic Unix lore. In some early proposals, an explicit option -n was added to disable the historical behavior of stripping NUL characters from the input. It was considered that automatically stripping NUL characters from the input was not correct functionality. However, the removal of -n in a later proposal does not remove the requirement that tr correctly process NUL characters in its input stream. And if you need those NUL characters gone? NUL characters can be stripped by using:

tr -d '\000'

Historical implementations of tr differ widely in syntax and behavior. For example, the BSD version has not needed the bracket characters for the repetition sequence. The tr utility syntax is based more closely on the System V and XPG3 model while attempting to accommodate historical BSD implementations. In the case of the short string2 padding, the decision was to unspecify the behavior and preserve System V and XPG3 scripts, which might find difficulty with the BSD method. The assumption was made that BSD users of tr have to make accommodations to meet the syntax defined here. Since it is possible to use the repetition sequence to duplicate the desired behavior, whereas there is no simple way to achieve the System V method, this was the correct, if not desirable, approach.

The use of octal values to specify control characters, while having historical precedents, is not portable. The introduction of escape sequences for control characters should provide the necessary portability. It is recognized that this may cause some historical scripts to break. ๐Ÿ˜ญ

An early proposal included support for multi-character collating elements. It was pointed out that, while tr does employ some syntactical elements from REs, the aim of tr is quite different; ranges, for example, do not have a similar meaning ("any of the chars in the range matches", versus "translate each character in the range to the output counterpart"). As a result, the previously included support for multi-character collating elements has been removed. What remains are ranges in current collation order (to support, for example, accented characters), character classes, and equivalence classes. ๐Ÿฆ‹

In XPG3 the [:class:] and [=equiv=] conventions are shown with double brackets, as in RE syntax. However, tr does not implement RE principles; it just borrows part of the syntax. Consequently, [:class:] and [=equiv=] should be regarded as syntactical elements on a par with [x*n], which is not an RE bracket expression.

The standard developers will consider changes to tr that allow it to translate characters between different character encodings, or they will consider providing a new utility to accomplish this. ๐Ÿ‘‘

On historical System V systems, a range expression requires enclosing square-brackets, such as:

tr '[a-z]' '[A-Z]'

However, BSD-based systems did not require the brackets, and this convention is used here to avoid breaking large numbers of BSD scripts:

tr a-z A-Z

The preceding System V script will continue to work because the brackets, treated as regular characters, are translated to themselves. However, any System V script that relied on "aโ€z" representing the three characters 'a', '-', and 'z' have to be rewritten as "az-".

The ISO POSIXโ€2:1993 standard had a -c option that behaved similarly to the -C option, but did not supply functionality equivalent to the -c option specified in POSIX.1โ€2008.

The earlier version also said that octal sequences referred to collating elements and could be placed adjacent to each other to specify multi-byte characters. However, it was noted that this caused ambiguities because tr would not be able to tell whether adjacent octal sequences were intending to specify multi-byte characters or multiple single byte characters. POSIX.1โ€2008 specifies that octal sequences always refer to single byte binary values when used to specify an endpoint of a range of collating elements.

Earlier versions of this standard allowed for implementations with bytes other than eight bits, but this has been modified in this version. ๐Ÿ’…


๐Ÿ”ฎ FUTURE DIRECTIONS ๐Ÿ”ฎ

None. Periodt. โœจ


๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

  • sed
  • The Base Definitions volume of POSIX.1โ€2017, Table 5-1, Escape Sequences and Associated Actions, Chapter 8, Environment Variables, Section 12.2, Utility Syntax Guidelines

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .

Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .

source/version: IEEE/The Open Group, 2017, TR(1POSIX). byeee bestie, stay iconic ๐Ÿ’…๐Ÿ’–

๐Ÿ“ฆ where this page comes from