- Linux Shell Scripting Cookbook(Third Edition)
- Clif Flynt Sarath Lakshman Shantanu Tushar
- 153字
- 2021-07-09 19:46:18
Complementing character sets
We can use a set to complement set1 using the -c flag. set2 is optional in the following command:
tr -c [set1] [set2]
If only set1 is present, tr will delete all characters that are not in set1. If set2 is also present, tr will translate characters that aren't in set1 into values from set2. If you use the -c option by itself, you must use set1 and set2. If you combine the -c and -d options, you only use set1 and all other characters will be deleted.
The following example deletes all the characters from the input text, except the ones specified in the complement set:
$ echo hello 1 char 2 next 4 | tr -d -c '0-9 \n' 124
This example replaces all characters that aren't in set1 with spaces:
$ echo hello 1 char 2 next 4 | tr -c '0-9' ' ' 1 2 4