Saturday, September 23, 2023
rated 0 times [  7] [ 0]  / answers: 1 / hits: 2527  / 9 Months ago, thu, january 5, 2023, 3:18:56

I have a ton of files named this way: [name]_[phonenumber]_HH-mm-ss_dd-MM-yyyy.mp3.
How can I shift [name] and [phonenumber] to the end of file name, and put the date in the beginning in form of yyyy-MM-dd_HH-mm-ss so I get yyyy-MM-dd_HH-mm-ss_[name]_[phonenumber]?

Here is an actual file name: [Unknown]_[+74999519075]_18-01-36_17-01-2014.mp3

I've tried rename, but due to lack of regexp knowledge I didn't come up with a working solution.

More From » command-line


This should work:

for i in *mp3; do rename 's/(.+?)_(.+?)_(.+?)-(.+?)-(.+?)_(.+?)-(.+?)-(.+?).mp3/$8-$7-$6_$3-$4-$5_$1_$2.mp3/' "$i"; done

The parentheses capture patterns. The 1st captured match is $1, the 2nd $2 etc. So, the command above:

  • will look for everything up to the first _

  • .+? means match the shortest pattern possible because of the ?,

  • then everything up to the 2nd _ etc.

  • and renames accordingly.

I tested it with:

$ touch [name]_[phonenumber]_HH-mm-ss_dd-MM-yyyy.mp3
$ ls
$ for i in *mp3; do rename 's/(.+?)_(.+?)_(.+?)-(.+?)-(.+?)_(.+?)-(.+?)-(.+?).mp3/$8-$7-$6_$3-$4-$5_$1_$2.mp3/' "$i"; done
$ ls

[#25559] Thursday, January 5, 2023, 9 Months  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 234
Total Questions: 124
Total Answers: 111

Location: Jordan
Member since Fri, Apr 8, 2022
1 Year ago