1. 程式人生 > 其它 >linux 中sed命令替換指定為此的字元

linux 中sed命令替換指定為此的字元

 

1、測試資料

[root@centos7 test4]# ls
test.txt
[root@centos7 test4]# cat test.txt
e f j f f
f d x s f
f d g f f
d e j k i
c f w f d

 

2、替換第一個f為xxx

[root@centos7 test4]# ls
test.txt
[root@centos7 test4]# cat test.txt
e f j f f
f d x s f
f d g f f
d e j k i
c f w f d
[root@centos7 test4]# sed 's/f/xxx/' test.txt  ## 替換提一個f為xxx
e xxx j f f xxx d x s f xxx d g f f d e j k i c xxx w f d [root@centos7 test4]# sed
's/f/xxx/1' test.txt ## 替換第一個f為xxx e xxx j f f xxx d x s f xxx d g f f d e j k i c xxx w f d

 

3、替換第n個f為xxx

[root@centos7 test4]# ls
test.txt
[root@centos7 test4]# cat test.txt
e f j f f
f d x s f
f d g f f
d e j k i
c f w f d
[root@centos7 test4]# sed 
's/f/xxx/2' test.txt ## 替換第二個f為xxx e f j xxx f f d x s xxx f d g xxx f d e j k i c f w xxx d [root@centos7 test4]# sed 's/f/xxx/3' test.txt ## 替換第三個f為xxx e f j f xxx f d x s f f d g f xxx d e j k i c f w f d

 

4、替換第二個至最後一個f都為xxx

[root@centos7 test4]# ls
test.txt
[root@centos7 test4]# cat test.txt
e f j f f
f d x s f
f d g f f
d e j k i
c f w f d
[root@centos7 test4]# sed 
's/f/xxx/2g' test.txt ## 替換第2個至最後一個f都為xxx e f j xxx xxx f d x s xxx f d g xxx xxx d e j k i c f w xxx d