Linux命令TR
tr介紹
tr - translate characters
是對sed功能的簡略版,能夠刪除和替換字符的一個簡易命令
tr [option] string1 [string2]
- -c -C –complement 填充除了你想要字符之外的character
- -d –delete 刪除
- -s –squeeze-repeats 替換
代碼實現
1 -c參數
echo file|tr -c 'fil' ' '
fil %
他會將出fil之外的字符自動補充成空字符串.
接下來看代碼是不是支持正則表達式
echo file|tr -c '[a-i]*' ' '
fi e %
2 -d
echo file|tr -d 'fil'
e %
換上正則試一試
echo file|tr -d '[a-i]*'
l %
3 -s
echo file|tr -s 'fil' 'tes'
tese %
換上正則試一試
echo file|tr -s '[a-i]*' 'tes'
sls %
多個參數的使用
大體上的使用就是上面的一些簡單操作,接下來試試看多個參數進行測試。我自己嘗試了一下能不能對多個文件進行tr,後來好像不太行,翻牆看了下文檔和man一下,上面說的是string,那麼我認爲應該是不能
tr [option] file1
這樣的結構的。
tr [-Ccsu] string1 string2
tr [-Ccu] -d string1
tr [-Ccu] -s string1
tr [-Ccu] -ds string1 string2
上面是多個參數的語法
echo abcdefg > a
tr -cd 'a'< a
a
換一個正則看看
echo abcdABCD > b
tr -cd '[a-cA-B]*' < b
abcAB%
根據結果,應該是顯示對哪些參數進行了處理。並且對大小寫敏感,如果你想要處理一堆大小寫混合的數據的話,最好先轉換成相同格式的在處理,tr有自帶的class對象,man下有很好的說明。我這就舉一個大小寫轉換的例子。
tr '[:lower:]' '[:upper:]' < b
ABCDABCD
這邊就一些入門的例子,記錄以便以後忘記,如果對其他class有興趣的話可以自己去看看。
[2]: man tr