Thursday, October 27, 2022

[SOLVED] Replacing a specific string from file names using bash

Issue

I am trying to replace a list of filenames inside a directory. For example

cd /home/towers
ls

c3_slo_live_ox_dns_m2m_pcg.yaml
c3_slo_live_ox_dns_service_pcg_physnet4.yaml
c3_slo_live_ox_dns_service_pcg_physnet2.yaml

to

cd /home/towers
ls

c3_dsd_live_ox_dns_m2m_pcg.yaml
c3_dsd_live_ox_dns_service_pcg_physnet4.yaml
c3_dsd_live_ox_dns_service_pcg_physnet2.yaml

Which is the best way? can we use sed? Any example that I should try? 

Solution

If you what you wanted is to rename the files according a replacement pattern you could try something like this:

for file in *;do mv $file $(echo $file|sed 's/_slo_/_dsd_/'); done
  • This will loop through every file in your current directory and replace the _slo_ string with _dsd_

I recommend you double check that this pattern isn't used unintentionally in other parts of your filenames before you commit to it.



Answered By - kiyell
Answer Checked By - Robin (WPSolving Admin)