Skip to content

Instantly share code, notes, and snippets.

@netj
Last active Mar 12, 2019
Embed
What would you like to do?
#!/usr/bin/env bash
# rename-audio-files.sh -- prints a shell script to rename .m4a, .mp3 files according to its tags
#
# Why/where would anyone use this:
# My car's USB audio (iDrive) works much better if the files are named with their metadata than the terse names (track-title) given by iTunes.
#
# Author: Jaeho Shin <netj@sparcs.org>
# Created: 2019-03-10
set -euo pipefail
{
type ffprobe
type jq
} >/dev/null
[[ $# -gt 0 ]] || set -- *
RENAME() { local "$@"; [[ "$FROM" -ef "$TO" ]] || mv -vf "$FROM" "$TO"; }
declare -p -f RENAME
find "$@" \( -name "*.m4a" -o -name "*.mp3" \) -print0 |
xargs -0 -L1 ffprobe -v quiet -print_format json -show_format -i |
# jq -c . | head | jq; exit #| # for debugging/quickiterations
jq '
.format |
(".\(.filename | sub(".*\\."; ""))") as $fileext |
(.tags |
[ .album // empty
, ([( (.disc | sub("/.*"; "")?)
, (.track | sub("/.*"; "")? | if tonumber < 10 then "0\(.)" else . end)
)] | join("."))
, .title
, .artist // empty
] | map(( gsub("[/]"; "-")
| sub("^[[:space:]]+"; "")
| sub("[[:space:]]+$"; "")
)?) | join("—") + $fileext
) as $normalized_name |
select(.filename != $normalized_name) |
@sh "RENAME TO=\($normalized_name)\tFROM=\(.filename)"
' -cr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment