Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux tr 命令詳解:字符轉換、刪除與壓縮實戰

編輯:Linux 教學

tr 定位

tr(translate)是 sed 的極簡變體:專注單字符替換、刪除、去重,語法極簡,無需正則表達式,腳本中極易嵌入。

核心語法

tr [OPTION]... SET1 [SET2]
  • SET1、SET2:字符集合,支持範圍(a-z)、字符類([:digit:])、轉義序列(\n、\t、\0)。
  • 無 SET2 時配合 -d 刪除,-s 壓縮。

常用選項

經典場景實戰

1. 大小寫轉換

echo "hello world" | tr a-z A-Z
# HELLO WORLD

在 vi 中可視模式選中行執行 :'<,'>!tr a-z A-Z 快速轉換。

2. 文件格式轉換(換行符)

選項功能示例
(無)字符映射替換(SET1→SET2)tr a-z A-Z 小寫轉大寫
-d刪除 SET1 中字符tr -d '\r' 刪除回車
-s壓縮連續重複字符為單個tr -s ' ' 多空格合一
-c / -C取補集(非 SET1 字符)tr -cd '[:print:]' 只保留可打印字符
來源格式行尾符轉換命令
Mac (Classic)\r (CR)tr '\r' '\n' < macfile > unixfile
Unix/Linux\n (LF)tr '\n' '\r' < unixfile > macfile
DOS/Windows\r\n (CRLF)tr -d '\r' < dosfile > unixfile

反向 Unix→DOS 需 awk:awk '{print $0"\r"}' < unixfile > dosfile(tr 不支持一字符換兩字符)。

3. 文本清理

  • 刪除制表符:tr -d '\t' < file
  • 壓縮多餘空格:tr -s ' ' < file
  • 合併多行為單行:tr -d '\n' < file(慎用,會丟失結構)

在 vi 中全文處理::%!tr -d '\t'。

4. ROT13 簡易加密

echo "secret" | tr 'a-zA-Z' 'n-za-mN-ZA-M'
# frperg

進階技巧

  • 字符類:[:alnum:]、[:alpha:]、[:digit:]、[:space:]、[:punct:]、[:print:]、[:cntrl:]、[:xdigit:]、[:lower:]、[:upper:]。
  • 八進制/十六進制:\123、\x1B 表示不可打印字符。
  • 補集配合刪除:tr -cd '[:print:]\n' < binary_file > clean_text 提取可打印文本。

tr 與 sed 選擇指南

  • 單字符映射/刪除/壓縮 → tr(更快、語法更簡潔)。
  • 需正則、按行處理、上下文相關替換 → sed。
  • 複雜多字符模式、字段操作 → awk。
Copyright © Windows教程網 All Rights Reserved