常用技巧
替换网址前缀
1
| sed 's/\(admin.*\)\.\([a-z]\{3\}\)\./a.\2./g' /etc/nginx/conf.d/admin.conf
|
\(\) 内的匹配为分组,可以使用 \1, \2, \3 来代替
例如:替换 adminfdsfdas.sdf.xxxxx.com 为 a.sdf.xxxxx.com
获取指定时间段日志
1
| sed -n '/11:11:/,/12:12:/p' filename
|
替换文件中所有字符串
1
| sed -i s/old/new/g filename
|
在匹配字符前插入内容
1
| sed -i 's/go/stark&/' file
|
在匹配字符后插入内容
1
| sed -i 's/go/&stark/' file
|
删除匹配行
1
| sed -i '/backup.sh/d' crontab
|
删除首尾行
在匹配行前插入
1
| sed -i '/qiao/i\gege' file
|
在匹配行后插入
1
| sed -i '/qiao/a\gege' file
|
替换整行
1
| sed -i '/root/c\rootbajie' /etc/passwd
|
在行首添加字符
1
| sed -i 's/^/HEAD&/' file
|
在行尾添加字符
1
| sed -i 's/$/&tail/' file
|
修改指定范围内容
1
| sed -i '/Begin/,/End/{s/xxx/ooo/g}' filename
|
字符串分段重排序
1
| sed 's/\(^[a-z_-]\+\):x:\([0-9]\+\):\([0-9]\+\):.*/\3 \1 \2/' passwd
|
技巧:使用自定义定界符
替换路径或网址时,转义符很多。sed 的定界符不只可以用 /,可以使用其他字符:
1 2 3 4 5 6 7 8 9 10 11 12
|
sed 's!/sbin/nologin!/bin/bash!' file
sed 's5/sbin/nologin5/bin/bash5' file
sed 'sz/sbin/nologinz/bin/bashz' file
|
任意不与替换内容重复的字符都可以作为定界符。