I want to do a search and replace within a file.
The search will be for a filename (within a text file) that its extension is .xml. Find the location by the .xml extension and change the text right before it.
i.e, f开发者_如何转开发ind this line with "emission_mazda_3_c1_zjz6_16_05_ho2s_front.xml" text and replace the text to "emission_mazda_3_c1_zjz6_16_04_ho2s_front.xml".
Any help will be appreciated, Thanks Tommy
It depends slightly on what you are using the regex in, so I have given a couple of examples.
Using BRE you could use:
s/\(emission_mazda_3_c1_zjz6_16_\)\(05\)\(_ho2s_front.xml\)/\104\3/
Which as Vim uses BRE, to do this on the whole document would be:
%s/\(emission_mazda_3_c1_zjz6_16_\)\(05\)\(_ho2s_front.xml\)/\104\3/
Or with sed, which also uses BRE, to output to stdout the file input.txt
with the replacements made:
sed -e 's/\(emission_mazda_3_c1_zjz6_16_\)\(05\)\(_ho2s_front.xml\)/\104\3/' input.txt
While with ERE you could use:
s/(emission_mazda_3_c1_zjz6_16_)(05)(_ho2s_front.xml)/\104\3/
The trick to all this is the use of backreferences. The text between the first two /
characters describes what you are looking for and is grouped by using the ()
characters. The text between the last two /
characters is what you want to replace it with. So you are saying replace the found text with the first group (\1
signifies this), then put 04
, then add the third group (\3
signifies this).
精彩评论