tr 命令
1. 參數:
-c, -C, --complement use the complement of SET1 -d, --delete delete characters in SET1, do not translate -s, --squeeze-repeats replace each input sequence of a repeated character that is listed in SET1 with a single occurrence of that character -t, --truncate-set1 first truncate SET1 to length of SET2 --help display this help and exit --version output version information and exit
-c: 取代SET1字符集中沒有包含的字符 -d: 刪除SET1字符集中所有的字符,不轉換 tr -d 'a' 輸入中含有a字符都會被刪除 -s: 壓縮SET1連續重複的字符 tr -s 'a' 把重複的連續字符處理成一個字符 -t: 將SET1 替換成SET2, 缺省爲-t tr -t "abc" "xyz" <==> tr "abc" "xyz"
2. 支持的正則表達式:
\NNN character with octal value NNN (1 to 3 octal digits) \\ backslash \a audible BEL \b backspace \f form feed \n new line \r return \t horizontal tab \v vertical tab CHAR1-CHAR2 all characters from CHAR1 to CHAR2 in ascending order [CHAR*] in SET2, copies of CHAR until length of SET1 [CHAR*REPEAT] REPEAT copies of CHAR, REPEAT octal if starting with 0 [: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
例子:
1. 將/etc/issue文件中的內容轉換爲大寫後保存到/tmp/issue文件中
tr 'a-z' 'A-Z' </etc/issue>/tmp/issue
2. 將登錄至當前系統上的用戶信息中的信息轉換爲大寫後保存至/tmp/who.out
who | tr '[[:lower:]]' '[[:upper:]]' > /tmp/who.out
3. 一個linux用戶給root發郵件要求郵件標題爲"help",郵件正文如下:Hello I am 用戶名,the system version is here, please help me to check it, thanks!
操作系統版本信息(跟tr無關)
mail -s "help" root <<EOF > Hello, I am $(whoami) > the system version is here, please help me to check it, thanks > $(cat /etc/redhat-release) > EOF
4.將/root/下文件列表,顯示成一行並文件名之間用空格隔開
ls /root | tr '\n' ' '
5. file1文件的內容爲"1 2 3 4 5 6 7 8 9 10" 計算出所有數字的總和
echo $[`cat file1 | tr ' ' '+'`] cat file | tr ' ' '+' | bc
6. 刪除Windows文本文件中的'^m'字符
tr -d '\r' < a.txt > LinuxTXT
7.處理字符串"xt.,|1 jr#!$mn 2 c*/fe 3 uz 4", 只保留其中的數字與空格
echo "xt.,|1 jr#4""mn 2 c*/fe 3 uz 4" | tr -d -c '[0-9] ' -c除了什麼不刪,其他的都要刪 除了[0-9]空格不刪,其它的都會刪除
8. 去重字符串"abcccd dedd"
echo "abcccd dedd" | tr -s '[[:alpha:]] ' 去重[a-z] 及空格