linux shell 字符替换命令

sed

文本 2.txt 内容如下:

shell 复制代码
1
2
3
4
5

11
121

abcabcc

1.替换文本指定字符或字符串,不更改原文件

将文本内容替换并输出,但不直接在原文档中修改: sed "s/旧字符串/新字符串/g" 文档

范例,将文本中的 1 替换为 b

shell 复制代码
root@heihei:/# sed "s/1/b/g" 2.txt
b
2
3
4
5

bb
b2b

abcabcc
root@heihei:/#

2.替换文本指定字符或字符串,不更改原文件,存储更改的内容到新文件

再次查看文档 2.txt,内容是没有变化的,想要储存就需要把结果另存到新的文件中

如下:

shell 复制代码
root@heihei:/# sed "s/1/b/g" 2.txt >> 3.txt
root@heihei:/# cat 3.txt
b
2
3
4
5

bb
b2b

abcabcc
root@heihei:/#

3.替换文本指定字符或字符串,直接更改原文件 加参数 -i即可

shell 复制代码
root@heihei:/# sed -i "s/1/b/g" 2.txt
root@heihei:/# cat 2.txt
b
2
3
4
5

bb
b2b

abcabcc
root@heihei:/#

4.替换文本指定字符或字符串,字符串为变量
sed "s/$old_str/$new_str/g" 文档

shell 复制代码
root@heihei:/# new_str='b'
root@heihei:/# old_str='1'
root@heihei:/# sed "s/$old_str/$new_str/g" 2.txt
b
2
3
4
5

bb
b2b

abcabcc

注意,需要用 双引号 "",假设用的单引号 ''

命令需要改成 sed 's/'$old_str'/'$new_str'/g' 文档

否则无法执行成功:

失败案例:

shell 复制代码
root@heihei:/# new_str='b'
root@heihei:/# old_str='1'
root@heihei:/# sed 's/$old_str/$new_str/g' 2.txt
1
2
3
4
5

11
121

abcabcc
root@heihei:/#

修改命令,成功达到预期结果

shell 复制代码
root@heihei:/# new_str='b'
root@heihei:/# old_str='1'
root@heihei:/# sed 's/'$old_str'/'$new_str'/g' 2.txt
b
2
3
4
5

bb
b2b

abcabcc
root@heihei:/#

5.这里记录一次用 tr -t "旧字符串" "新字符串"进行替换时遇到的坑

tr -t "旧字符" "新字符" 应该是这样的作用,接字符串时会出现问题

他的作用等同于sed "s/旧字符串/新字符串/g" 文档,但是如果接字符串时,并不是我认为的

将符合的字符串进行替换,而是依旧按照单字符挨个替换,如下

如下:

shell 复制代码
root@sh-z390-01:~/test/sed# x="0010086,sds"
root@sh-z390-01:~/test/sed# echo $x |tr -t "10086" "01472"
4404472,sds
root@sh-z390-01:~/test/sed# echo $x |tr -t "10086" "01"
1101186,sds

如上面的例子,我们指定了旧字符串 "10086",新字符串"01472"

但实际执行下来是将$x中所有的 1 更改为了0,所有的0 改成了1随后又被改为了4 ,8改成7,6改成2

实际上是按照

1 --> 0

0 --> 1

0 --> 4

8 --> 7

6 --> 2

这样的映射关系进行的单字符替换

相关推荐
Johny_Zhao1 小时前
Docker + CentOS 部署 Zookeeper 集群 + Kubernetes Operator 自动化运维方案
linux·网络安全·docker·信息安全·zookeeper·kubernetes·云计算·系统运维
小毛驴8502 小时前
Linux 后台启动java jar 程序 nohup java -jar
java·linux·jar
一心0923 小时前
ubuntu 20.04.6 sudo 源码包在线升级到1.9.17p1
运维·ubuntu·sudo·漏洞升级
好好学习啊天天向上3 小时前
世上最全:ubuntu 上及天河超算上源码编译llvm遇到的坑,cmake,ninja完整过程
linux·运维·ubuntu·自动性能优化
你想考研啊4 小时前
三、jenkins使用tomcat部署项目
运维·tomcat·jenkins
tan180°4 小时前
MySQL表的操作(3)
linux·数据库·c++·vscode·后端·mysql
代码老y4 小时前
Docker:容器化技术的基石与实践指南
运维·docker·容器
典学长编程5 小时前
Linux操作系统从入门到精通!第二天(命令行)
linux·运维·chrome
wuk9985 小时前
基于MATLAB编制的锂离子电池伪二维模型
linux·windows·github
你想考研啊7 小时前
四、jenkins自动构建和设置邮箱
运维·jenkins