For example, the content in abcd.txt is as follows:
[root@i-B56C455B DMS]# more abcd.txt aba1 abcd acad [root@i-B56C455B DMS]#
Now replace all a with e: use [/ g]
[root@i-B56C455B DMS]# sed -i 's/a/e/g' abcd.txt [root@i-B56C455B DMS]# more abcd.txt ebe1 ebcd eced [root@i-B56C455B DMS]#
Now only replace the first occurrence of e in each line as a: remove [/ g]
[root@i-B56C455B DMS]# sed -i 's/e/a/' abcd.txt [root@i-B56C455B DMS]# more abcd.txt abe1 abcd aced [root@i-B56C455B DMS]#
Perform it again and replace e with a:
[root@i-B56C455B DMS]# sed -i 's/e/a/' abcd.txt [root@i-B56C455B DMS]# more abcd.txt aba1 abcd acad [root@i-B56C455B DMS]#
It is now implemented to replace only one a at a time: use [0, / content to be replaced / s / content to be replaced / replace content /], and only replace the first a in the first line as e
[root@i-B56C455B DMS]# sed -i '0,/a/s/a/e/' abcd.txt
[root@i-B56C455B DMS]# more abcd.txt
eba1
abcd
acad
[root@i-B56C455B DMS]#
Now back to the original content:
[root@i-B56C455B DMS]# more abcd.txt aba1 abcd acad [root@i-B56C455B DMS]#
To replace all a in the first line with e, combined with the above, you only need to add the / g parameter:
[root@i-B56C455B DMS]# sed -i '0,/a/s/a/e/g' abcd.txt
[root@i-B56C455B DMS]# more abcd.txt
ebe1
abcd
acad
[root@i-B56C455B DMS]#
Okay, what if you want to replace two lines each time? Then change 0, / to 1,
[root@i-B56C455B DMS]# more abcd.txt aba1 abad acad [root@i-B56C455B DMS]#
Try replacing two lines:
[root@i-B56C455B DMS]# sed -i '1,/a/s/a/e/g' abcd.txt [root@i-B56C455B DMS]# more abcd.txt ebe1 ebed acad [root@i-B56C455B DMS]#
Restore the original content, replacing two lines at a time, replacing only the first a to e:
[root@i-B56C455B DMS]# more abcd.txt aba1 abad acad [root@i-B56C455B DMS]# sed -i '1,/a/s/a/e/' abcd.txt [root@i-B56C455B DMS]# more abcd.txt eba1 ebad acad [root@i-B56C455B DMS]#