-1

I want to rename a lot of files in sub directories with a shell script/command, and I've tried different way without any success.

Here is the files I've got:

root/FOLDER1/media-125150-payasage151.jpg
root/FOLDER1/media-125165-payasage125.jpg
root/FOLDER2/media-1266165-payasage110.jpg
root/FOLDER2/media-1266165-portrait151.jpg

and I want to replace every "payasage" by "paysage"

root/FOLDER1/media-125150-paysage151.jpg
root/FOLDER1/media-125165-paysage125.jpg
root/FOLDER2/media-1266165-paysage110.jpg
root/FOLDER2/media-1266165-portrait151.jpg

I've tried RegExr with rename command or even with a mv approch... thanks!

Antoine
  • 472
  • 2
  • 11
  • 21

1 Answers1

-1

Try something along the lines of

for OLD in root/*/media-*-payasage*.jpg; do
  NEW=$(echo "$OLD" | sed 's/payasage/paysage/g')
  test "$OLD" != "$NEW" && mv "$OLD" "$NEW"
done
Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
  • Unnecessary sed usage. Use `NEW="${OLD//payasage/paysage}"`. [Bash String Manipulation](https://www.tldp.org/LDP/abs/html/string-manipulation.html) – RedX Apr 05 '19 at 09:14
  • Unnecessary indeed - but readability trumps efficiency in this setting: The rename itself will take orders of magnitude more resources than the `sed` – Eugen Rieck Apr 05 '19 at 09:15
  • On windows: `time for ((i = 0; i < 100; ++i)); do OLD="haha"; echo "$OLD" | sed "s/ha/hu/g" > /dev/null; done`: 3.9s whereas `time for ((i = 0; i < 100; ++i)); do OLD="haha"; echo "${OLD//ha/hu}" > /dev/null; done`: 0.006s – RedX Apr 05 '19 at 09:19
  • On Windows this might be true.The question is tagged as `linux` though – Eugen Rieck Apr 05 '19 at 09:20
  • I was hoping you would copy paste this in your linux environment :) So we could compare. – RedX Apr 05 '19 at 09:21
  • Ah, I see: `real 0m0.047s / user 0m0.004s / sys 0m0.023s` vs. `real 0m0.004s / user 0m0.004s / sys 0m0.000s` on Ubuntu 18.04 – Eugen Rieck Apr 05 '19 at 09:23
  • Summary: for only a few times you won't notice a difference but if you have many renames to do, using sed is 10x slower (in this example). – RedX Apr 05 '19 at 09:27
  • That is plain wrong: The syscall to rename the file itself takes orders of magnitude longer, so the only thing taking longer is a tiny fraction of the total. Expect a less than 0.1% slowdown in real-world cases – Eugen Rieck Apr 05 '19 at 09:35
  • I agree. I can't edit my comment anymore unfortunately. – RedX Apr 05 '19 at 09:36
  • No problem - maybe this discussion is a good reference for future searchers – Eugen Rieck Apr 05 '19 at 09:38