linux shell实现将匹配字符行的最后一个字符替换为指定字符

 

1、测试数据

root@PC1:/home/test/test# ls
test.txt
root@PC1:/home/test/test# cat test.txt  ## 实现将每行最后一个e替换为xxx
e r e y e u e
e e g e 3 h r
1 3 e g e y e
e s e e e e e

 

2、while 循环 + sed实现

复制代码
root@PC1:/home/test/test# ls
test.txt
root@PC1:/home/test/test# cat test.txt
e r e y e u e
e e g e 3 h r
1 3 e g e y e
e s e e e e e
root@PC1:/home/test/test# awk '{print NR,gsub(/e/,"&")}' test.txt  ## 统计每行e的数目,并加行号
1 4
2 3
3 3
4 6
root@PC1:/home/test/test# awk '{print NR,gsub(/e/,"&")}' test.txt > index.txt
root@PC1:/home/test/test# ls
index.txt  test.txt
root@PC1:/home/test/test# cat index.txt
1 4
2 3
3 3
4 6
root@PC1:/home/test/test# cp test.txt test.txt_bak  ## 备份原始文件
root@PC1:/home/test/test# cat index.txt | while read {i,j}; do sed -i "$i s/e/xxx/$j" test.txt; done  ## 利用while循环 + sed 实现
root@PC1:/home/test/test# cat test.txt  ## 最后一个e全部替换为xxx了
e r e y e u xxx
e e g xxx 3 h r
1 3 e g e y xxx
e s e e e e xxx
复制代码

 

3、如果一行中没有e

复制代码
root@PC1:/home/test/test# ls
test.txt
root@PC1:/home/test/test# cp test.txt test.txt_bak
root@PC1:/home/test/test# ls
test.txt  test.txt_bak
root@PC1:/home/test/test# cat test.txt
e r e y e u e
d a f g 3 h r
1 3 e g e y e
e s e e e e e
root@PC1:/home/test/test# awk -F "e" '{print NR, NF - 1}' test.txt ## 统计每行e的数目,并添加行号
1 4
2 0
3 3
4 6
root@PC1:/home/test/test# awk -F "e" '{print NR, NF - 1}' test.txt | awk '$2 != 0'  ## 过滤掉没有e的行
1 4
3 3
4 6
root@PC1:/home/test/test# awk -F "e" '{print NR, NF - 1}' test.txt | awk '$2 != 0' > index.txt
root@PC1:/home/test/test# cat index.txt
1 4
3 3
4 6
root@PC1:/home/test/test# cat index.txt | while read {i,j}; do sed -i "$i s/e/xxx/$j" test.txt; done  ## 利用while循环 + sed对最后一个e进行替换
root@PC1:/home/test/test# cat test.txt  ##最后一个e替换为了xxx
e r e y e u xxx
d a f g 3 h r
1 3 e g e y xxx
e s e e e e xxx
复制代码

 

posted @   小鲨鱼2018  阅读(2176)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2020-12-15 linux系统中部署Samba服务(实现linux系统之间文件共享)
2020-12-15 python中字符串的合并(f字符串,在变量中使用字符串)
2020-12-15 python中删除字符串开头和结尾的空白
2020-12-15 python中字符串大小写转换
2020-12-15 linux系统中安装TFTP服务(简单文件传输协议)
点击右上角即可分享
微信分享提示