sed and awk学习笔记一



一:

Sed的使用方式主要参考下面的格式:

[address][command]/pattern/replacement/flag

address是指运用于那些行,如果不特别指出的话就是运用到所有的行

command是具体的要如何操作的命令。主要有以下几个命令

a:新增, a的后面可以接字串,而这些字串会在新的一行出现(目前的下一行)

c:取代, c的后面可以接字串,这些字串可以取代 n1,n2之间的行!

d:删除,因为是删除啊,所以 d后面通常不接任何咚咚;

i:插入, i的后面可以接字串,而这些字串会在新的一行出现(目前的上一行)

p:列印,亦即将某个选择的数据印出。通常 p会与参数 sed -n一起运行~

s:取代,可以直接进行取代的工作哩!通常这个s的动作可以搭配正规表示法!

/pattern/replacement:其中pattern是正则表达式中的pattern是一个意思,就是找到要对其进行操作的字符。Replacement就是要替换的字符

Flag:是修饰替换的标识。有下面几个作用:

n1512之间的一个数字,表示对文本模式中指定模式第n次出现的情况进行替换

g:全局更改

p:打印模式空间的内容

w:将模式空间的内容写到文件中去

 

 

下面我们来看下具体的使用:

假设我有这样的一篇文档:

This is a linuxsed/awk test file,the operate system is linux

linux is a operate system that can doanything

我想将其中的linux换成windows. 其中包含3linux词语。首先建立prj1.sed文件。其中脚本为:s/linux/windows/

我们来看下运行的结果:

可以看到第一行的第一个linux以及第二行的linux都被替换成了windows。但是第一行的第二个linux并没有被替换。证明这个命令只涉及每一行中出现的第一个pattern,其他的pattern都没有涉及.

$ sed -f prj1.sed prj1.txt
This is a windows sed/awk test file,theoperate system is windows
windows
is a operate system that can doanything



如果想替换所有的pattern,脚本改为s/linux/windows/g.可以看到结果就符合预期了。其中g的作用在于替换每行中所有符合的pattern



$ sed -f prj1.sed prj1.txt
This is a windows sed/awk test file,theoperate system is windows
windows
is a operate system that can doanything




再继续修改脚本:/This/s/linux/windows/g添加了地址信息。也就是只有在包含This的行才会被应用替换命令。下面的结果可以看到只有第一行的信息被替换了




$ sed -f prj1.sed prj1.txt
This is a windows sed/awk test file,theoperate system is windows
linux is a operate system that can do anything



我们还可以指定具体的行范围。比如1,2 s/linux/windows/g这里表明就是将1-2行的字符进行替换:

$ sed -fprj1.sed prj1.txt
This is a windows sed/awk test file,theoperate system is windows
windows
is a operate system that can doanything

如果我们只是想替换第一行第二次出现的linux字符,该如何操作呢。这里就要用到flag修饰符了。脚本修改为:/This/s/linux/windows/2

$ sed -fprj1.sed prj1.txt
This is a linux sed/awk test file,the operate system is windows
linux is a operate system that can do anything

最后来看下flagp的作用,这个其实就是将符合模式的哪一行内容重新打印了出来

/This/s/linux/windows/p这里可以看到多出来一行。就是p的打印



$ sed -f prj1.sed prj1.txt
This is a windows sed/awk test file,the operate system is linux
This is a windows sed/awk test file,the operate system is linux
linux is a operate system that can do anything





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿玩AI

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值