sed用法

sed 用法
/ /开启匹配模式
a
sed '1,3a\hello world' 1.txt 1-3行追加hello
sed '/3/a\hello' 1.txt 匹配3追加hello

i
sed '1i\hello' 1.txt 第一行前插入
sed '/3/i\hello' 1.txt 匹配插入
d
sed '1d' 1.txt
sed '/3/d' 1.txt
sed -r '/^#|#|^$/d' my.cnf -r 正则 删除以#开头,包含,以空格开头的
s 替换

sed -i '/super/s/server/100%/g'  xx   匹配super那一行,并把那一行的server替换成100% 

【此处我遇到了一个bug,在做字符串拼接时,python的格式化字符串问题】

cmd = "sed -i '/super/s/server/100%/g' %s"%file
os.popen(cmd)
#此时代码会报错,因为%的问题,在做字符串拼接时,如果有%,需要写成100%%,如下
cmd = "sed -i '/super/s/server/100%%/g' %s"%file

sed -i 's/old/old:\n  a:b/g'  file

#此处如果是放在cmd变量去供脚本语言调用,需要多加一个\用来转义,如下

cmd = "sed -i 's/old:/old:\\n a:b' %s"%file

  

 


sed 's/cat/dog/' 1.txt
sed '2,4s/cat/dog/' 1.txt
sed '/3 the/s/cat/dog/' 1.txt 匹配的那行换掉
c 改
sed 'c\hello' 1.txt 默认全改
sed '2,4c\hello' 1.txt 把2-4删了 改为hello
sed '/3 the/c\hello' 1.txt 匹配改
y 转换
sed 'y/cat/TCA/' 1.txt
sed 'p' 1.txt 会打印两遍


flag: 2,g,w
sed 's/dog/cat/2' file
sed 's/dog/cat/g' file 全部替换
sed -n '3s/dog/cat/p' file 不会打印文本内容,只会打印改的 -n抑制内存输出 -p打印
sed -i '/dog/cat/g' file -i 修改原文件,不可逆
sed -i.bak '/dog/cat/g' file -i .bak可以修改前创建备份

sed -n '$=' file 打印多少行

 

posted @ 2021-08-15 01:22  绣幕  阅读(54)  评论(0编辑  收藏  举报