Skip to Content
bash shell脚本编程经典实例 (第2版)
book

bash shell脚本编程经典实例 (第2版)

by Carl Albing, JP Vossen
January 2021
Intermediate to advanced
581 pages
15h 7m
Chinese
Posts & Telecom Press
Content preview from bash shell脚本编程经典实例 (第2版)
中级
shell
工具(续)
173
8.9
 转换字符
8.9.1
 问题
你需要将文本中出现的某个字符全部转换成另一个字符。
8.9.2
 解决方案
可以使用
tr
命令。例如:
tr ';' ',' <be.fore >af.ter
8.9.3
 讨论
就其最简单的形式而言,
tr
命令用第二个参数的第
1
个(仅此)字符替换第一个参数的第
1
个(仅此)字符。
在上述示例中,我们将输入重定向为文件
be.fore
,将输出重定向至文件
af.ter
,将输入文件
中所有的分号替换成了逗号。
为什么要在分号和逗号两边使用单引号呢?这是因为分号在
bash
中有特殊含义,如果不用
引号,那么
bash
会将命令拆成两个,这肯定要出错。逗号倒是没有特殊含义,将它放入引
号纯粹出于习惯,免得万一忘记什么。坚持使用引号会更安全,这样就永远不会漏写了。
如果使用多个待转换的字符作为第一个参数,要转换成的字符作为第二个参数,那么
tr
命令就会一次性执行多个字符转换。记住,这种转换是一对一进行的。例如:
tr ';:.!?' ',' <other.punct >commas.all
该命令会将分号、冒号、句号、惊叹号、问号全部转换成逗号。因为第二个参数比第一个
参数短,所以不断重复第二个参数的最后一个字符(这个例子中就只有一个)来匹配第一
个参数的长度,这样一来,字符就能在转换时一一对应了。
sed
命令也能完成这种转换,只不过语法有点麻烦。
tr
命令没有那么厉害,因为它无法使
用正则表达式,但
tr
有一些特别的字符区间语法,非常有用,
8.10
节将对其进行介绍。
8.9.4 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

bash 网络安全运维

bash 网络安全运维

Paul Troncone, Carl Albing
Linux 内核观测技术BPF

Linux 内核观测技术BPF

David Calavera, Lorenzo Fontana

Publisher Resources

ISBN: 9787115553782