1

So I have a script I am trying to write. It takes all .mp3 files from a directory and moves them to another directory and names them in numerical order, like 0001.mp3, 0002.mp3, ect.

i=0
for f in *.mp3; do
i=$((i+1));
mv "$f" "/home/jwt13/Testing/$(printf %04d $i).mp3";
done

Now I am trying to have it so the above command does the move and rename based on how old to file is. So it will take the oldest file and name it 0001, the second oldest would be 0002. How can I go about doing that using the above script? Would I be able to add lines into this or would I need to re-write the entire thing a different way?

Thank you

3
  • do you have zsh available? It's available on RHEL, but not always installed by default.
    – Jeff Schaller
    Commented Nov 1, 2019 at 17:52
  • I do not. I thought zsh was a little different from bash?
    – thango
    Commented Nov 1, 2019 at 18:02
  • zsh is a little different from bash; it has more powerful rename capabilities as well as wildcard expansion features that could innately sort the filenames by modification time. Bash has neither of those, which is why I asked :)
    – Jeff Schaller
    Commented Nov 1, 2019 at 18:11

1 Answer 1

3

You can just change *.mp3 into $(ls -rt *.mp3):

i=0
for f in $(ls -rt *.mp3); do
    i=$((i+1));
    mv "$f" "/home/jwt13/Testing/$(printf %04d $i).mp3";
done

-t sorts files by modification time, and -r makes the oldest file come first.

As mentioned by @Jeff, the above doesn't work when filenames contain weird characters. In that case, you should use this(still can't handle newline characters):

i=0
ls -rt *.mp3 |
while read -r f; do
    i=$((i+1));
    mv "$f" "/home/jwt13/Testing/$(printf %04d $i).mp3";
done

where output of ls is piped into the whole while loop.

4
  • 2
    unless any of those filenames have space, tab, newline, or wildcard characters in them...
    – Jeff Schaller
    Commented Nov 1, 2019 at 17:48
  • Oh god I cant believe it was that simple. I was thinking I would need an entire new line of commands. Thanks so much for the quick response.
    – thango
    Commented Nov 1, 2019 at 17:55
  • Wound the find command handle newline characters?
    – thango
    Commented Nov 4, 2019 at 19:20
  • @thango -print0 and -exec options can, but find can’t sort files by time.
    – sdp
    Commented Nov 5, 2019 at 1:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .