sed中引用变量时候注意事项
1.匹配模式中存在变量,则建议使用双引号
2.sed中需要引入自定义变量时,如果外面使用的是单引号,则自定义变量也必须使用单引号
编辑命令对照表
类别 编辑命令 含义
查询 p 打印
---------------------------------------------------------------------
a 行后追加
i 行前追加
增加 r 外部文件读入,行后追加
w 匹配行写入外不文件
---------------------------------------------------------------------
删除 d 删除
---------------------------------------------------------------------
s/old/new 将第一行的old替换为new
s/old/new/g 将行内全部的old替换为new
修改 s/old/new/2g 将行内的从第2个开始到最后old替换为new
s/old/new/ig 将行内old全部替换为new ,忽略大小写
示例:
不会对源文件进行删除
$ sed -n '1d' passwd
修改源文件删除第一行
$ sed -i '1d' passwd
删除第一行到第三行
$ sed -i '1,3d' passwd
删除不能登录的用户 匹配/sbin/nologin
$ sed -i '/\/sbin\/nologin/d' passwd
删除 nologin和mail 之间的行
$ sed -i '/^nologin/,/^mail/d' passwd
在所有匹配到行的文件追加一句话到文件中
$ sed -i '/\/home1\/yinxiong/a This is user which can login to system' passwd
将list文件中内容追加到 passwd 匹配行中
& sed -i '/root/r list' passwd
将符合条件的行保存包aa文件中
sed -n "/yinxiong/w aa" passwd
将小写的 bin/bash 替换为BIN/BASH
sed -i 's/\/bin/bash/\BIN\/BASH/g' passwd
使用&符号获取old值 将匹配到的 had..p/&s 替换为 had..ps , &符号只能进行整个符号计算
$ sed -i 's/had..p/&s/g' str.txt
使用\1的代替&的时候需要将 被代替的文字用 () 括起来 括号需要转义
$ sed -i 's/\(had..p\)/\1s/g' str.txt
替换hadXXXXX为hadoop
$ sed -i 's/\(had\)...../\1doop/g' str.txt
匹配模式中存在变量,则建议使用双引号
#!/bin/bash
old_str=hadoop
new_str=HADOOP
sed -i "s/$old_str/$new_str/g" str.txt
sed中需要引入自定义变量时,如果外面使用的是单引号,则自定义变量也必须使用单引号
#!/bin/bash
old_str=hadoop
new_str=HADOOP
sed -i 's/'$old_str'/'$new_str'/g' str.txt