sed字符串对象【替换】

时间:2022-10-16 09:01:06

sed字符串替换

[position]s/source/destination/flags

Position is optional

 

一、S Specific Parameters

1&

[nick@d01 bash]$ cat sedrep.txt

w1

test my car

[nick@d01 bash]$sed -e 's/w1/w2/g' sedrep.txt

w2

test my car

[nick@d01 bash]$sed -e 's/w1/&w2/g' sedrep.txt

w1w2

test my car

 

 

2/n

[nick@d01 bash]$ cat sedrep.txt

w1

test my car

[nick@d01 bash]$ sed -e 's//(test/)/(my/)/(car/)//2/3/1/' sedrep.txt

w1

mycartest

 

Blue font string matchs “test my car”. And there are two blanks among/(test/), /(my/) and /(car/).

/(…./) is used to keep the value which may be referenced by number index.

 

二、Flags Parameters

(1)   g

replace in global space

[nick@d01 bash]$ cat sedrep.txt

w1 w1 w1 w1 w1 w1

test my car

w1 w1 w1

w1

[nick@d01 bash]$sed -e 's/w1/&w2/g' sedrep.txt

w1w2 w1w2 w1w2 w1w2 w1w2 w1w2

test my car

w1w2 w1w2 w1w2

w1w2

 

(2)   number

replace the nth string in this line

[nick@d01 bash]$ cat sedrep.txt

w1 w1 w1 w1 w1 w1

test my car

w1 w1 w1

w1

[nick@d01 bash]$sed -e 's/w1/&w2/2' sedrep.txt

w1 w1w2 w1 w1 w1 w1

test my car

w1 w1w2 w1

w1

[nick@d01 bash]$ sed -e 's/w1/&w2/1' sedrep.txt

w1w2 w1 w1 w1 w1 w1

test my car

w1w2 w1 w1

w1w2

 

(3)   p

replace the ith string in every line and print out

[nick@d01 bash]$ cat sedrep.txt

w1 w1 w1 w1 w1 w1

test my car

w1 w1 w1

w1

[nick@d01 bash]$sed -e 's/w1/&w2/p' sedrep.txt

w1w2 w1 w1 w1 w1 w1

w1w2 w1 w1 w1 w1 w1

test my car

w1w2 w1 w1

w1w2 w1 w1

w1w2

w1w2

 

(4)   w

write the result to one file

[nick@d01 bash]$ cat sedrep.txt

w1 w1 w1 w1 w1 w1

test my car

w1 w1 w1

w1

[nick@d01 bash]$ sed -e 's/w1/&w2/2w sedrep2.txt' sedrep.txt

w1 w1w2 w1 w1 w1 w1

test my car

w1 w1w2 w1

w1

 

三、Optional Position Parameter

[nick@d01 bash]$ cat sedrep.txt

w1 w1 w1 w1 w1 w1

test my car w1

w1 w1 w1

w1

[nick@d01 bash]$sed -e '/car/s/w1/&w2/g' sedrep.txt

w1 w1 w1 w1 w1 w1

test my car w1w2

w1 w1 w1

w1

[nick@d01 bash]$sed -e '1,/car/s/w1/&w2/g' sedrep.txt

w1w2 w1w2 w1w2 w1w2 w1w2 w1w2

test my car w1w2

w1 w1 w1

w1

[nick@d01 bash]$sed -e '/car/,3s/w1/&w2/g' sedrep.txt

w1 w1 w1 w1 w1 w1

test my car w1w2

w1w2 w1w2 w1w2

w1

[nick@d01 bash]$sed -e '1,2s/w1/&w2/g' sedrep.txt

w1w2 w1w2 w1w2 w1w2 w1w2 w1w2

test my car w1w2

w1 w1 w1

w1

 


sed -i write changes into file directly