tr#

tr (Translate) 是包含在 GNU Coreutils 內的字元轉換與刪除工具。

tr 是 Linux 系統中用於「轉換」或「刪除」字元的指令。它從標準輸入(Standard Input)讀取資料,根據設定的字元集進行對應替換後輸出。常配合管線(pipe)處理文字的大小寫轉換、刪除特定符號或壓縮連續重複的字元。

Install#


Setting in up#


Operate#

tr [options] [set1] [set2]

小寫轉大寫#

echo “hello” | tr ‘a-z’ ‘A-Z’

刪除所有數字#

echo “user123” | tr -d ‘0-9’

壓縮重複的空白(將多個空白變成一個)#

echo “hello world” | tr -s ’ '

將冒號替換為換行#

echo $PATH | tr ‘:’ ‘\n’

參數範例指令說明
-dtr -d '0-9'刪除字元。刪除所有匹配的字元(如數字)。
-str -s ' '壓縮重複。將連續重複字元減縮為一個。
-ctr -cd 'a-z'補集操作。配合 -d 使用時,可刪除「除了指定字元以外」的所有內容。
-ttr -t 'abc' 'd'截斷對應。強迫轉換集合長度一致。
格式說明範例
tr 'a-z' 'A-Z'小寫轉大寫echo "linux" | tr 'a-z' 'A-Z'
tr -d '\n'刪除所有換行cat list.txt | tr -d '\n'
tr -s '\n'刪除空白行cat file.txt | tr -s '\n'
tr ' ' '\n'將空格換成換行echo "a b c" | tr ' ' '\n'

Reference#

Official docs: