tr 명령어 (AIX 5.3·6.1)
https://archive.horanglab.com/posts/aix-cmd-tr
핵심 정리
- 표준 입력의 문자를 바꾸거나 지워 표준 출력에 씁니다. 파일 이름을 받지 않으므로
< 파일로 넘깁니다. tr 'a-z' 'A-Z'는 String1의 문자를 String2의 같은 자리 문자로 바꿉니다.-d는 String1의 문자를 지우고,-s는 연속된 같은 문자를 하나로 줄입니다.-c·-C는 String1의 여집합(그 밖의 모든 문자)을 씁니다.- 특수 표기:
C1-C2(범위),[C*N](반복),[C*](String1 길이만큼 채우기),[:lower:]같은 문자 클래스,[=C=](동치 클래스),\8진수,\n·\t같은 제어 문자. -A는 현재 로캘 대신 ASCII 순서로 바이트 단위로 처리합니다. 범위 표기는 로캘의 영향을 크게 받습니다.- AIX 5.3과 6.1 문서의 내용이 같습니다.
| 항목 | 내용 |
|---|---|
| 버전 | AIX 5.3, AIX 6.1 (두 버전 내용 같음) |
| 원문 | IBM Commands Reference — 5.3 Volume 5, 6.1 Volume 5 |
| 파일 | /usr/bin/tr |
| 관련 명령어 | trbsd, sed, ed |
목적
문자를 바꿉니다.
영어 원문
Translates characters.
구문
tr [ -c | -cds | -cs | -C | -Cds | -Cs | -ds | -s ] [ -A ] String1 String2
tr { -cd | -cs | -Cd | -Cs | -d | -s } [ -A ] String1
설명
tr 명령은 표준 입력의 문자를 지우거나 바꿔 결과를 표준 출력에 씁니다. String1과 String2 변수, 그리고 지정한 플래그에 따라 세 가지 일을 합니다.
문자 바꾸기
String1과 String2를 모두 지정하고 -d 플래그가 없으면, 표준 입력에서 String1에 든 문자를 String2의 같은 자리 문자로 바꿉니다.
-d로 문자 지우기
-d 플래그를 지정하면 표준 입력에서 String1에 든 문자를 지웁니다.
-s로 연속 문자 줄이기
-s 플래그를 지정하면 String1이나 String2가 나타내는 문자가 연속으로 나올 때 첫 문자만 남기고 지웁니다. String1의 문자는 표준 입력에서, String2의 문자는 표준 출력에서 연속된 것 중 첫 문자만 남깁니다.
문자열을 나타내는 특수 표기
String1과 String2의 문자열은 다음 규칙으로 쓸 수 있습니다.
| 표기 | 뜻 |
|---|---|
C1-C2 |
대조 순서에서 C1부터 C2까지(양끝 포함)의 문자들입니다. C1이 C2보다 앞서야 합니다. 이 방법으로 범위를 지정하면 결과가 현재 로캘의 영향을 크게 받으므로, 로캘과 상관없이 같은 결과가 필요하면 범위를 쓰지 않는 것이 좋습니다. |
[C*Number] |
문자 C를 Number번 되풀이합니다. Number는 10진 정수이며, 첫 숫자가 0이면 8진 정수로 봅니다. |
[C*] |
문자 C로 문자열을 채웁니다. String2의 끝에만 쓰며, String2를 String1과 같은 길이로 만듭니다. * 뒤의 문자는 무시합니다. |
[:ClassName:] |
현재 로캘에서 ClassName 문자 클래스에 든 모든 문자입니다. 클래스 이름은 alnum, alpha, blank, cntrl, digit, graph, lower, print, punct, space, upper, xdigit입니다. |
[=C=] |
문자 C와 같은 동치 클래스에 든 모든 문자입니다. |
\Octal |
1~3자리 8진수 Octal로 나타낸 인코딩의 문자입니다. NULL 문자는 '\0'으로 나타내며 다른 문자처럼 처리합니다. |
\ControlCharacter |
제어 문자입니다. \a(경고), \b(백스페이스), \f(폼 피드), \n(줄바꿈), \r(캐리지 리턴), \t(탭), \v(세로 탭). |
\\ |
이스케이프 문자로서의 뜻 없이 \(백슬래시) 자체입니다. |
\[ |
특수 표기의 시작이라는 뜻 없이 [(왼쪽 대괄호) 자체입니다. |
\- |
범위 구분자라는 뜻 없이 -(빼기) 자체입니다. |
문자 클래스: [:lower:]와 [:upper:] 변환 클래스를 빼면, 다른 문자 클래스의 문자는 정해지지 않은 순서로 배열에 들어갑니다. 그래서 여러 문자를 한 문자로 바꿀 때만 쓰는 것이 좋습니다. 문자 클래스는 ctype 서브루틴을 참고합니다.
String1에 같은 문자가 여러 번 나오면, String1에서 마지막으로 나온 자리에 대응하는 String2의 문자로 바꿉니다.
String1과 String2의 길이가 다르면 긴 쪽의 남는 문자는 무시합니다.
영어 원문
The tr command deletes or substitutes characters from standard input and writes the result to standard output. The tr command performs three kinds of operations depending on the strings specified by the String1 and String2 variable and on the flags specified.
Transforming Characters
If String1 and String2 are both specified and the -d flag is not specified, the tr command replaces each character contained in String1 from the standard input with the character in the same position in String2.
Deleting Characters Using the -d Flag
If the -d flag is specified, the tr command deletes each character contained in String1 from standard input.
Removing Sequences Using the -s Flag
If the -s flag is specified, the tr command removes all but the first character in any sequence of a character string represented in String1 or String2. For each character represented in String1, the tr command removes all but the first occurrence of the character from standard output. For each character represented in String2, the tr command removes all but the first occurrence in a sequence of occurrences of that character in the standard output.
Special Sequences for Expressing Strings
The strings contained in the String1 and String2 variables can be expressed using the following conventions:
- C1
-C2 — Specifies the string of characters that collate between the character specified by C1 and the character specified by C2, inclusive. The character specified by C1 must collate before the character specified by C2. Note: The current locale has a significant effect on results when specifying subranges using this method. If the command is required to give consistent results irrespective of locale, the use of subranges should be avoided. - [
C*Number] — Number is an integer that specifies the number of repetitions of the character specified by C. Number is considered a decimal integer unless the first digit is a 0; then it is considered an octal integer. - [
C*] — Fills out the string with the character specified by C. This option, used only at the end of the string contained within String2, forces the string within String2 to have the same number of characters as the string specified by the String1 variable. Any characters specified after the*(asterisk) are ignored. - [ :ClassName: ] — Specifies all of the characters in the character class named by ClassName in the current locale. The class name can be any of the following names:
alnum lower alpha print blank punct cntrl space digit upper graph xdigitExcept for [:lower:] and [:upper:] conversion character classes, the characters specified by other character classes are placed in the array in an unspecified order. Because the order of the characters specified by character classes is undefined, the characters should be used only if the intent is to map several characters into one. An exception to this is the case of conversion character classes. For more information on character classes, see the ctype subroutines. - [ =C= ] — Specifies all of the characters with the same equivalence class as the character specified by C.
\Octal— Specifies the character whose encoding is represented by the octal value specified by Octal. Octal can be a one-, two- or three-digit octal integer. The NULL character can be expressed with'\0', and is processed like any other character.\ControlCharacter— Specifies the control character that corresponds to the value specified by ControlCharacter. The following values can be represented:\aAlert\bBackspace\fForm-feed\nNew line\rCarriage return\tTab\vVertical tab\\— Specifies the\(backslash) as itself, without any special meaning as an escape character.\[— Specifies the [ (left bracket) as itself, without any special meaning as the beginning of a special string sequence.\-— Specifies the - (minus sign) as itself, without any special meaning as a range separator.
If a character is specified more than once in String1, the character is translated into the character in String2 that corresponds to the last occurrence of the character in String1.
If the strings specified by String1 and String2 are not the same length, the tr command ignores the extra characters in the longer string.
플래그
| 플래그 | 설명 |
|---|---|
-A |
범위와 문자 클래스에 현재 로캘의 대조 순서 대신 ASCII 대조 순서를 써서, 모든 작업을 바이트 단위로 합니다. |
-C |
String1을 String1의 여집합으로 바꿉니다. 여집합은 현재 로캘의 문자 집합에서 String1의 문자를 뺀 모든 문자입니다. -d를 지정하지 않으면 여집합 문자를 현재 LC_COLLATE가 정한 대조 순서의 오름차순으로 배열에 넣습니다. |
-c |
String1을 String1의 여집합으로 바꿉니다. -d를 지정하지 않으면 여집합 값을 2진 값의 오름차순으로 배열에 넣습니다. |
-d |
표준 입력에서 String1에 든 문자를 모두 지웁니다. |
-s |
연속으로 되풀이된 문자 중 첫 문자만 남깁니다. String1의 연속 문자는 바꾸기 전에 표준 입력에서, String2의 연속 문자는 표준 출력에서 줄입니다. |
| String1 | 문자열을 지정합니다. |
| String2 | 문자열을 지정합니다. |
-c·-C 공통: -A와 함께 쓰면 8비트 문자 코드 전체를 기준으로 여집합을 구합니다. -s와 함께 쓰면 -s는 String1의 여집합 문자에 적용됩니다.
-d의 참고:
-C와-d를 함께 쓰면 String1에 지정한 문자를 뺀 모든 문자를 지웁니다.-s도 지정하지 않으면 String2는 무시합니다.-c와-d를 함께 쓰면 String1에 지정한 값을 뺀 모든 값을 지웁니다.-s도 지정하지 않으면 String2는 무시합니다.
영어 원문
-A— Performs all operations on a byte-by-byte basis using the ASCII collation order for ranges and character classes, instead of the collation order for the current locale.-C— Specifies that the value of String1 be replaced by the complement of the string specified by String1. The complement of String1 is all of the characters in the character set of the current locale, except the characters specified by String1. If the-Aand-cflags are both specified, characters are complemented with respect to the set of all 8-bit character codes. If the-cand-sflags are both specified, the-sflag applies to characters in the complement of String1. If the-doption is not specified, the complements of the characters specified by String1 will be placed in the array in ascending collation sequence as defined by the current setting ofLC_COLLATE.-c— Specifies that the value of String1 be replaced by the complement of the string specified by String1. The complement of String1 is all of the characters in the character set of the current locale, except the characters specified by String1. If the-Aand-cflags are both specified, characters are complemented with respect to the set of all 8-bit character codes. If the-cand-sflags are both specified, the-sflag applies to characters in the complement of String1. If the-doption is not specified, the complement of the values specified by String1 will be placed in the array in ascending order by binary value.-d— Deletes each character from standard input that is contained in the string specified by String1. Note: 1. When the-Coption is specified with the-doption, all characters except those specified by String1 will be deleted. The contents of String2 are ignored unless the-soption is also specified. 2. When the-coption is specified with the-doption, all values except those specified by String1 will be deleted. The contents of String2 are ignored unless the-soption is also specified.-s— Removes all but the first in a sequence of a repeated characters. Character sequences specified by String1 are removed from standard input before translation, and character sequences specified by String2 are removed from standard output.- String1 — Specifies a string of characters.
- String2 — Specifies a string of characters.
종료 상태
| 값 | 뜻 |
|---|---|
| 0 | 모든 입력을 잘 처리했습니다. |
| 0보다 큼 | 오류가 났습니다. |
영어 원문
This command returns the following exit values:
- 0 — All input was processed successfully.
>0— An error occurred.
예제
- 중괄호를 괄호로 바꿉니다.
{를(로,}를)로 바꾸고 다른 문자는 그대로 둡니다.
tr '{}' '()' < textfile > newfile
- 중괄호를 대괄호로 바꿉니다.
{를[로,}를]로 바꿉니다. 왼쪽 대괄호는\(백슬래시)로 이스케이프해야 합니다.
tr '{}' '\[]' < textfile > newfile
- 소문자를 대문자로 바꿉니다.
tr 'a-z' 'A-Z' < textfile > newfile
- 파일의 단어 목록을 만듭니다. 소문자와 대문자가 아닌 문자가 이어진 부분을 줄바꿈 하나로 바꿉니다.
*가 줄바꿈을 둘째 문자열이 첫째 문자열만큼 길어지도록 되풀이합니다.
tr -cs '[:lower:][:upper:]' '[\n*]' < textfile > newfile
- 파일에서 NULL 문자를 모두 지웁니다.
tr -d '\0' < textfile > newfile
- 연속된 줄바꿈을 줄바꿈 하나로 바꿉니다. 다음 둘 중 하나를 씁니다.
tr -s '\n' < textfile > newfile
tr -s '\012' < textfile > newfile
- 올바른 제어 문자를 뺀, 인쇄할 수 없는 문자를 모두
?(물음표)로 바꿉니다. 다른 로캘에서 만든 파일에서 현재 로캘로는 인쇄할 수 없는 문자를 찾을 때 씁니다.
tr -c '[:print:][:cntrl:]' '[?*]' < textfile > newfile
space문자 클래스의 문자가 이어진 부분을#하나로 바꿉니다.
tr -s '[:space:]' '[#*]'
관련 명령어: trbsd, ed
영어 원문
- To translate braces into parentheses, type:
tr ’{}’ ’()’ < textfile > newfile
This translates each { (left brace) to ( (left parenthesis) and each } (right brace) to ) (right parenthesis). All other characters remain unchanged.
- To translate braces into brackets, type:
tr ’{}’ ’\[]’ < textfile > newfile
This translates each { (left brace) to [ (left bracket) and each } (right brace) to ] (right bracket). The left bracket must be entered with a \ (backslash) escape character.
- To translate lowercase characters to uppercase, type:
tr ’a-z’ ’A-Z’ < textfile > newfile
- To create a list of words in a file, type:
tr -cs ’[:lower:][:upper:]’ ’[\n*]’ < textfile > newfile
This translates each sequence of characters other than lowercase letters and uppercase letters into a single newline character. The * (asterisk) causes the tr command to repeat the new line character enough times to make the second string as long as the first string.
- To delete all NULL characters from a file, type:
tr -d ’\0’ < textfile > newfile
- To replace every sequence of one or more new lines with a single new line, type:
tr -s ’\n’ < textfile > newfile
OR tr -s ’\012’ < textfile > newfile
- To replace every nonprinting character, other than valid control characters, with a ? (question mark), type:
tr -c ’[:print:][:cntrl:]’ ’[?*]’ < textfile > newfile
This scans a file created in a different locale to find characters that are not printable characters in the current locale.
- To replace every sequence of characters in the
<space>character class with a single # character, type:tr -s ’[:space:]’ ’[#*]’
Related reference:
- trbsd Command
Related information:
- ed command
- ctype command
- National Language Support Overview
리눅스(GNU)와 다른 점
| 항목 | AIX 5.3·6.1 | GNU tr |
|---|---|---|
-C와 -c |
-C는 대조 순서, -c는 2진 값 순서로 여집합을 둠 |
둘 다 같은 뜻 |
-A |
ASCII 바이트 단위 처리 | 없음 |
| 다중 바이트 문자 | 로캘에 맞춰 문자 단위로 처리 | 바이트 단위로만 처리 |
AIX에는 BSD 방식의 trbsd 명령이 따로 있습니다. AIX 5.3·6.1 문서에는 -t(String1을 String2 길이로 자름) 같은 GNU 플래그가 없습니다.