Linux Bash 中的 tr 命令
Yahya Irmak 2023年1月30日 Linux Bash Linux Command Bash Command
- 在 Linux Bash 中使用
tr命令翻譯字串 - 在 Linux Bash 中使用
-d標誌刪除字元 - 在 Linux Bash 中使用
-s標誌壓縮字元 - 在 Linux Bash 中使用
-c標誌排除 Set - 從 Linux Bash 中的
cat命令獲取輸入
在 Linux 中,我們可以使用 Bash 指令碼進行字串操作,例如連線、截斷和在文字中查詢單詞。
本文將解釋如何在 Linux Bash 中使用 tr 命令翻譯或刪除字元。
在 Linux Bash 中使用 tr 命令翻譯字串
tr 命令的意思是翻譯。它用於刪除、翻譯和壓縮字元。
它接受標準輸入,對其進行處理,然後將其寫入標準輸出。
語法:
tr '[SET1]' '[SET2]' 這裡,SET1 代表要在文字中找到的字母,SET2 代表要替換的字母。
例如,我們可以使用以下命令之一將所有小寫字母轉換為大寫。
echo "lowercase string" | tr '[:lower:]' '[:upper:]' echo "lowercase string" | tr '[a-z]' '[A-Z]' 與此相反:
echo "UPPERCASE STRING" | tr '[A-Z]' '[a-z]' echo "UPPERCASE STRING" | tr '[:upper:]' '[:lower:]' 
對於查詢和替換的使用:
echo "test string with dash" | tr ' ' '-' 使用此命令,將找到作為輸入的文字中的所有空格字元並將其替換為破折號。
test-string-with-dash 在 Linux Bash 中使用 -d 標誌刪除字元
-d 標誌用於刪除字元,而不是翻譯它們。它採用單個字符集並從文字中刪除這些字元。
`echo "hxexlxlxo" | tr -d 'x'` 輸出:
hello 在 Linux Bash 中使用 -s 標誌壓縮字元
-s 標誌將文字中的連續字元轉換為該字元的單次出現。
echo "tttessttt sstriinngg" | tr -s 'a-z' 輸出:
test string 在 Linux Bash 中使用 -c 標誌排除 Set
-c 標誌將除 SET1 中指定的字元之外的所有字元轉換為 SET2 中的字元。
`echo "a1@b2'c3&d" | tr -c '[a-z]' ' '` 輸出:
a b c d 從 Linux Bash 中的 cat 命令獲取輸入
你可以使用 tr 命令更改檔案的內容。我們可以使用 cat 命令讀取檔案並將其內容通過管道傳輸到 tr 命令。
cat file.txt | tr '-' ' ' 
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Yahya Irmak
Yahya Irmak has experience in full stack technologies such as Java, Spring Boot, JavaScript, CSS, HTML.
LinkedIn