0

I have the following script that renames files based on a specific file name string. The script was working fine until I had to apply it to a directory that contains a folder name with a space.

Script:

for file in `find /home/splunkLogs/Captin/PPM\ Images/PXT  -type f -name '*.jpg'`; do mv -v "$file" "${file/-0.jpg/_Page_1.jpg}"; done

You'll notice the file name "PPM Images", which has a space. I added a backslash so the path would be readable, but I get the error "mv: cannot stat /home/splunkLogs/Captin/PPM: No such file or directory. I also tried putting the folder name in quotes in the path and received the same error. Can anyone guide me with a solution for handling filename spaces with the MV command?

mannj2018
  • 83
  • 6
  • 1
    You don't read lines with `for` this ain't `python` – Jetchisel Apr 21 '20 at 22:49
  • @Whoever closed this: this is asking for move _and rename_. The other answers don't have that detail. – rtx13 Apr 21 '20 at 23:01
  • 1
    @rtx13: I don't have a view on the closure, but bear in mind that closures do not have to be precise. If proposed duplicate(s) would get a question author 90% of the way to a solution, then they are good enough to close the question, in my view. We generally expect question authors to do some legwork with answers anyway - surely we want to discourage copy-paste usage of answers from here, which can lead to all sorts of problems, e.g. with security. – halfer Apr 21 '20 at 23:24
  • @rtx13 ... this is a site for Q&A that are relevant to more than one person; anyone who comes here with an expectation to get a tailored response to their exact use-case is doing it wrong. Both offered up duplicates should make it abundantly clear how to work around the issue without spelling the whole thing out verbatim. – tink Apr 21 '20 at 23:30
  • (note to self 3ddf25ca491b60fa4af9a1c2927b23eb) – rtx13 Apr 22 '20 at 01:58
  • @Whoever linked other questions: how is the linked https://stackoverflow.com/questions/57447644/exactly-how-do-backslashes-work-within-backticks question relevant to this question? – rtx13 Apr 22 '20 at 05:27

1 Answers1

3

So do not read lines using for. Read https://mywiki.wooledge.org/BashFAQ/001 .

find /home/splunkLogs/Captin/PPM\ Images/PXT  -type f -name '*.jpg' |
while IFS= read -r file; do
     mv -v "$file" "${file/-0.jpg/_Page_1.jpg}"
done

or better:

find /home/splunkLogs/Captin/PPM\ Images/PXT  -type f -name '*.jpg' -print0 |
while IFS= read -r -d '' file; do
     mv -v "$file" "${file/-0.jpg/_Page_1.jpg}"
done

Do not use backticks `. Using $(...) instead is greatly preferred.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111