tr 命令替换字符的工作原理

2021-08-13  本文已影响0人  小屁孩云熙

tr 命令替换信息是 1对1 的替换

欲替换的字符长度 大于 替换后的字符长度

# "abcd" > "123"
a   -   1
b   -   2
c   -   3
d   -   3

1233

[yunxuan@yunxuanedu ~]$ echo "abcd"|tr "abcd" "123"
1233

[yunxuan@yunxuanedu files]$ cat test.txt 
abcd
[yunxuan@yunxuanedu files]$ tr "abcd" "123" < test.txt 
1233
[yunxuan@yunxuanedu files]$ cat test.txt 
abcd
# 无法替换修改文件内容
image-20210812232835911.png

欲替换的内容字符数 小于 替换后的内容的字符数

# "abc" < "1234"

a   -   1
b   -   2
c   -   3

123

[yunxuan@yunxuanedu files]$ echo "abcd"|tr "abc" "1234"
123d
[yunxuan@yunxuanedu files]$ cat test.txt 
abcd
[yunxuan@yunxuanedu files]$ tr "abc" "123" < test.txt 
123d
image-20210812233843414.png

欲替换的内容字符数 等于 替换后的内容的字符数

# "abc" = "123"
[yunxuan@yunxuanedu files]$ echo "abcd" | tr "abcd" "1234"
1234
[yunxuan@yunxuanedu files]$ cat test.txt 
abcd
[yunxuan@yunxuanedu files]$ tr "abcd" "1234" < test.txt 
1234
image-20210813000459941.png

特殊情况

# 案例 1
[yunxuan@yunxuanedu files]$ echo "abcba"|tr "abcba" "12345"
54345

"abcba" "12345"
a   -   1
b   -   2
c   -   3
b   -   4
a   -   5

abcba -> 54345

# 案例二
[yunxuan@yunxuanedu files]$ echo "yunxuan"|tr "yunxuan" "admin"
anninnn

"yunxuan" "admin"
y   -   a
u   -   d
n   -   m
x   -   i
u   -   n
a   -   n
n   -   n

yunxuan --> anninnn

# 案例三
[yunxuan@yunxuanedu files]$ cat test.txt 
abcdef
abcbad
[yunxuan@yunxuanedu files]$ tr "abcd" "12345" < test.txt 
1234ef
123214

a   -   1
b   -   2
c   -   3
d   -   4

abcdef -> 1234ef
abcbad -> 123214

[yunxuan@yunxuanedu files]$ cat test.txt 
abcdef
abcbad
[yunxuan@yunxuanedu files]$ tr "abcd" "123" < test.txt 
1233ef
123213

a   -   1
b   -   2
c   -   3
d   -   3

abcdef  -> 1233ef
abcbad  -> 123213
image-20210813000412719.png
上一篇 下一篇

猜你喜欢

热点阅读