typora/note/Shell/sed 搜索替换.md

78 lines
1.6 KiB
Markdown
Raw Permalink Normal View History

2024-12-11 21:48:55 -05:00
### 语法
- sed 选项 's/搜索的内容/替换的内容/动作' 需要处理的文件
- 动作
- p 打印
- g 全局替换
```
me@me-EQ59:~/shell_demo$ cat file1
lfla
fla
flavnanv
rpprp
dbdfblbjaljl;ka
me@me-EQ59:~/shell_demo$ sed -n 's/fla/FLA/p' file1
lFLA
FLA
FLAvnanv
me@me-EQ59:~/shell_demo$ sed -n '1s/fla/FLA/p' file1
lFLA
me@me-EQ59:~/shell_demo$ sed -n '1s/fla/FLA/g' file1
me@me-EQ59:~/shell_demo$ sed -n '1s/fla/FLA/gp' file1
lFLA
me@me-EQ59:~/shell_demo$
```
- 替换 /user/local 为 lalala
```
me@me-EQ59:~/shell_demo$ cat file1
lfla
fla
flavnanv
rpprp
/usr/local
/user/local/bin
dbdfblbjaljl;ka
me@me-EQ59:~/shell_demo$ sed -n 's@/user/local@lalala@gp' file1
lalala/bin
me@me-EQ59:~/shell_demo$ sed -n 's#/user/local#lalala#gp' file1
lalala/bin
me@me-EQ59:~/shell_demo$
```
- 一到五行替换成#号
```
me@me-EQ59:~/shell_demo$ cat file1
lfla
fla
flavnanv
rpprp
/usr/local
/user/local/bin
dbdfblbjaljl;ka
me@me-EQ59:~/shell_demo$ sed -n '1,5s/^/#/gp' file1
#lfla
#fla
#flavnanv
#rpprp
#/usr/local
me@me-EQ59:~/shell_demo$
```
- 10.1.1.1 替换成 10.1.1.254
```
me@me-EQ59:~/shell_demo$ cat ip.txt
10.1.1.1
10.2.2.2
me@me-EQ59:~/shell_demo$ sed -n 's/10.1.1.1/10.1.1.254/gp' ip.txt
10.1.1.254
me@me-EQ59:~/shell_demo$ sed -n 's/\(10.1.1.\)1/\1254/gp' ip.txt
10.1.1.254 # 小括号括起来,保留为第一个正则表达式,后续使用 \1 来使用刚才保存的值
me@me-EQ59:~/shell_demo$ sed -n 's#\(10.1.1.\)1#\1254#gp' ip.txt
10.1.1.254
me@me-EQ59:~/shell_demo$
```
- sed 结合正则
![3af55d15a2738c93e1728f5ca9edb2e0.png](../../_resources/3af55d15a2738c93e1728f5ca9edb2e0.png)