-1

I want to replace part of filename with specified character.

For example:

$ ls
SubNetwork=RNCRAM955E,MeContext=RNCRAM955E_statsfile.xml

I want to replace RNCRAM955E with RNCMST954E

Here comes my expected output.

$ ls
SubNetwork=RNCMST954E,MeContext=RNCMST954E_statsfile.xml

and below is my code:

$ find ./ -name '*.xml' | xargs -i echo mv {} {} | sed 's/RNCRAM955E/RNCMST954E/3g' | sh

mv ./SubNetwork=RNCRAM955E,MeContext=RNCRAM955E_statsfile.xml ./SubNetwork=RNCMST954E,MeContext=RNCMST954E_statsfile.xml
mv ./SubNetwork=RNCRAM955E,MeContext=RNCRAM955E_statsfile.xml ./SubNetwork=RNCMST954E,MeContext=RNCMST954E_statsfile.xml
mv ./SubNetwork=RNCRAM955E,MeContext=RNCRAM955E_statsfile.xml ./SubNetwork=RNCMST954E,MeContext=RNCMST954E_statsfile.xml 
mv ./SubNetwork=RNCRAM955E,MeContext=RNCRAM955E_statsfile.xml ./SubNetwork=RNCMST954E,MeContext=RNCMST954E_statsfile.xml

I can't understand what's the code of 3g exactly mean.

In my opinion: Does the sed s/xx/xx/3g means replace match pattern from the 3rd one to the end ,and the sed s/xx/xx/3 means only replace the 3rd match pattern? BTW, what's the exactly mean of |sh, I think it makes the command after echo as a shell executing, right ?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
huang cheng
  • 393
  • 3
  • 15

1 Answers1

0

3 means to substitute the 3rd match, and g means to substitute all matches. When you use them together it means to substitute all matches starting at the 3rd one.

Piping to sh means to execute the output of sed as shell commands.

Most Linux distributions have a rename command that makes this easier:

find . -name '*.xml' -exec rename 's/RNCRAM955E/RNCMST954E/' {} +
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks for your kindly explain, but why I type your command , there was no effect? could you please explain the `+` to me ? and why the `-exec` without end character `\;`? – huang cheng May 22 '18 at 02:26
  • `+` instead if `\;` means to run the command once with all the filenames as arguments, instead of running it separately for each file. – Barmar May 22 '18 at 02:31
  • See https://stackoverflow.com/questions/6085156/using-semicolon-vs-plus-with-exec-in-find?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Barmar May 22 '18 at 02:31
  • There are different versions of `rename` depending on the Linux distro. Check the man page for your version to see how to use it to do what you want. – Barmar May 22 '18 at 02:32
  • get it . type `rename RNCRAM955E RNCMST954E *RNCRAM955E*` twice is ok. – huang cheng May 22 '18 at 02:46