美文网首页
Sed学习笔记2

Sed学习笔记2

作者: dming1024 | 来源:发表于2019-04-24 10:26 被阅读0次

sed有以下几种常用的工作模式:
-n,静态处理命令,不涉及的行不打印;
-e,默认选项,把sed后的输入当做命令来执行;
-i,会直接修改文件;
-r,扩展正则表达式。
直接讲述实例:

cat sedExample.txt#输出文件查看一下内容,第一行是空行

today is May
today date is 24th May
today is Wednesday
what day is it today
what a beautiful
it is the last day of the word

打印指定的行(含有May字符的行)

cat sedExample.txt |sed -n '/May/p'
today is May
today date is 24th May

打印指定的行,加上-e,结果也一样,所以一般情况下可以省略-e

cat sedExample.txt |sed -ne '/May/p'
today is May
today date is 24th May

删除指定的行(含有May字符的行)

cat sedExample.txt |sed '/May/d'

today is Wednesday
what day is it today
what a beautiful
it is the last day of the word

删除以what开头的行

cat sedExample.txt |sed '/^what/d'

today is May
today date is 24th May
today is Wednesday
it is the last day of the word

先删除空行,再删除以May结尾的行,这个时候-e是不能省略的

cat sedExample.txt |sed -e '/^$/d' -e '/May/d'
today is Wednesday
what day is it today
what a beautiful
it is the last day of the word

或者,对命令加上{}

cat sedExample.txt |sed  '{/^$/d; /May/d}'
today is Wednesday
what day is it today
what a beautiful
it is the last day of the word

在today前添加this

cat sedExample.txt |sed  's/today/this &/'

this today is May
this today date is 24th May
this today is Wednesday
what day is it this today
what a beautiful
it is the last day of the word

在May后添加 Liunx

cat sedExample.txt |sed  's/May/& Linux/'

today is May Linux
today date is 24th May Linux
today is Wednesday
what day is it today
what a beautiful
it is the last day of the word

在有what行的行首,加上#

cat sedExample.txt |sed  '/what/s/^/#/'

today is May
today date is 24th May
today is Wednesday
#what day is it today
#what a beautiful
it is the last day of the word

在有day单词行的行尾部,加上#

cat sedExample.txt |sed  '/\<day\>/s/$/#/'

today is May
today date is 24th May
today is Wednesday
what day is it today#
what a beautiful
it is the last day of the word#

注意,以上的操作均未改动原文件

cat sedExample.txt

today is May
today date is 24th May
today is Wednesday
what day is it today
what a beautiful
it is the last day of the word

如果要改动原文件需要加上-i

此外sed还有一个比较6的功能,就是批量更改文件名
列出文件下的.txt文件

ls *.txt
dna.txt  geoMatrix.txt  geox.txt  gg.txt  sedExample.txt  x.txt

将geo...txt文件,改成GEO...txt

ls *.txt|sed -n 's/\(geo\(.*\)\)/mv \1 GEO\2/p'
mv geoMatrix.txt GEOMatrix.txt
mv geox.txt GEOx.txt

ls *.txt|sed -n 's/\(geo\(.*\)\)/mv \1 GEO\2/p'|bash
ls *.txt
dna.txt  GEOMatrix.txt  GEOx.txt  gg.txt  sedExample.txt  x.txt

相关文章

网友评论

      本文标题:Sed学习笔记2

      本文链接:https://www.haomeiwen.com/subject/vokwgqtx.html