linux sed 应用实例,sed命令简单使用示例分享

sed是“stream editor”的缩写,也就是流编辑器,它一次处理一行内容,处理时,把当前处理的行存储在临时缓冲区中,称为“模式空间”(pattern space),接着用sed

处理缓冲区中的内容,处理完成后,把缓冲区的内容送往屏幕。接着处理下一行,这样不断重复,直到文件末尾。文件内容并没有 改变,除非你使用重定向存储输出。

92bb8ced7d4a90e971e33be2384795d0.png

使用Sed进行文本文件更改的示例

假设您有一个名为linuxidc.com.txt的文件,其中包含以下行:

1, linux idc, Title 639, Price $9.30

2, linuxidc ninhao, Title 761, Price $5.90

3, linuxmi nihao, Title 880, Price $9.30

4, linuxmi com, Title 198, Price $1.30

5, Johnny Cash, Title 582, Price $6.50

6, Elvis Presley, Title 370, Price $9.30

7, John Lennon, Title 571, Price $8.90

8, Michael Jackson, Title 673, Price $7.50

9, linuxidc com, Title 585, Price $1.80

您想要将所有价格变动9.30美元更改为8.88美元。 为此,您可以通过以下方式使用sed命令:

linuxidc@Ubuntu:~/linuxidc.com$ sed 's/9.30/8.88/' linuxidc.com.txt > linuxidc.txt

此代码进行更改并将修改后的文件保存为linuxidc.txt。 生成的新文件包含:

linuxidc@ubuntu:~/linuxidc.com$ cat linuxidc.txt

1, linux idc, Title 639, Price $8.88

2, linuxidc ninhao, Title 761, Price $5.90

3, linuxmi nihao, Title 880, Price $8.88

4, linuxmi com, Title 198, Price $1.30

5, Johnny Cash, Title 582, Price $6.50

6, Elvis Presley, Title 370, Price $8.88

7, John Lennon, Title 571, Price $8.90

8, Michael Jackson, Title 673, Price $7.50

9, linuxidc com, Title 585, Price $1.80

8c7a6fe7f1ee4878a5e51a1ab86a18e7.png

如果你想用“linuxidc”替换所有出现的“linuxmi”,你也可以用这种方式使用sed命令:

linuxidc@ubuntu:~/linuxidc.com$ sed 's/linuxmi/linuxidc/' linuxidc.com.txt > linuxidc.txt

生成的修改文件linuxidc.txt将包含以下文本:

linuxidc@ubuntu:~/linuxidc.com$ cat linuxidc.txt

1, linux idc, Title 639, Price $9.30

2, linuxidc ninhao, Title 761, Price $5.90

3, linuxidc nihao, Title 880, Price $9.30

4, linuxidc com, Title 198, Price $1.30

5, Johnny Cash, Title 582, Price $6.50

6, Elvis Presley, Title 370, Price $9.30

7, John Lennon, Title 571, Price $8.90

8, Michael Jackson, Title 673, Price $7.50

9, linuxidc com, Title 585, Price $1.80

e24c1be723ff7054866ffd3317736ae4.png

使用Sed命令过滤

Sed也经常用于过滤文件中的行。 例如,如果您只想查看包含“linuxidc”的行,则可以使用以下sed命令:

linuxidc@ubuntu:~/linuxidc.com$ sed -n '/linuxidc/p' linuxidc.com.txt > linuxidc.txt

新的linuxidc.txt文件将包含以下行:

linuxidc@ubuntu:~/linuxidc.com$ cat linuxidc.txt

2, linuxidc ninhao, Title 761, Price $5.90

9, linuxidc com, Title 585, Price $1.80

4a400ecd068368c7b7835d28d343cbb1.png

原文来自:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值