Linux sed命令的基本使用方法

Linux sed命令的基本使用方法

sed命令是利用脚本来处理文本文件,可以依照脚本的指令去处理、编辑文本文件。sed命令主要是用来自动编辑一个或多个文件、简化对文件的反复操作,并且支持正则表达式去匹配。
SED is a powerfull text stream editor.Can do insertion,deletion,search and replace(substitution);
SED command in unix supports regular expression which allows it perform complex pattern matching.
语法:

sed OPTIONS...[SCRIPT] [INPUTFILE]

参数说明:
a:新增,a的后面可以接字符串,这些字符串会在新的一行出现(当前的下一行);
c:替换,c的后面可以接字符串,这些字符串可以替换n1,n2之间的行;
d:删除,d后面不需要写东西;
i:插入,i的后面可以接字符串,这些字符串会在新的一行出现(当前的上一行);
p:打印,将选择的数据打印输出;
s:取代,可以搭配正则 1,10s/old/new/g

示例:

#test.txt
linux is great os,unix is opensource.unix is free os.
learn operating system.
linux unix which one you choose.
linux is easy to learn,unix is a multiuser os.Learn unix,unix is a powerfull os.
#replacing or substituting string
sed 's/linux/unix/' test.txt	
#将test.txt文件中每一行的第一个linux都替换成unix

sed 's/linux/unix/2' test.txt	
#将test.txt文件的每一行的第二个linux都替换成unix

sed 's/linux/unix/g' test.txt	
#将test.txt文件中所有的linux都替换成unix,g->global replacement

sed 's/linux/unix/3g' test.txt	
#将test.txt文件中每一行的第三个linux和第三个后面的linux都替换成unix

sed 's/\(\b[A-Z]\)/\(\1\)/g' test.txt
#将test.txt大中写的A-Z加上()

sed '3 s/linux/unix/' test.txt
#将test.txt文件中的第三行的linux替换成unix

sed 's/linux/unix/p' test.txt
#将有被替换的行打印两遍,没有被替换的打印一遍
#the /p print flag prints the replaces line twice on the terminal.
#If a line does not have the search pattern and is not replaced,then the /p prints that line only once.

sed -n 's/linux/unix/p' test.txt 
#只打印被替换的行
#Use the -n option along with the /p print flag to display only the replaced lines.
#Here the -n option sup presses the duplicate rows generated by the /p flag and prints the replaced lines only one time.

sed '1,3 s/linux/unix/' test.txt
#将test.txt中的第一行到第三行的linux替换成unix
sed '2,$ s/linux/unix' test.txt
#将test.txt中的第二行之后的linux替换成unix
#Replacing string on a range of lines:you can specify  a range of line numbers to sed command for replacing a string.
#deleting lines
sed '2d' test.txt
#删除test.txt文件中的第二行
sed '$d' test.txt
#删除test.txt文件中的最后一行
sed '3,5d' test.txt
#删除test.txt文件中的第3行到第五行(to delete a range of lines)
sed '2,$d' test.txt
#删除test.txt文件中的第二行到最后一行(to delete from nth to the last line)
sed '/pattern/d' test.txt
#删除test.txt文件中包含pattern的行(to delete pattern matching line)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值