I have a music collection organized like ./Music/Genre/Artist/Album/Disk#/song.flac. I want to add an ALBUMARTIST tag to every FLAC file, using the Artist directory from its path as the value. However, I only want to add the tag when the file does not already have one. For example, a file under ./Music/Soapy Argyle/Album/... should receive ALBUMARTIST=Soapy Argyle. How can I extract that directory name and safely combine it with find and metaflac without overwriting existing tags?
2 Answers
You can split each path into its components, check whether the file already has an album artist tag, and only then run metaflac. This version prints the commands first as a dry run: `find Music -type f -name '*.flac' -print | while IFS= read -r songfile; do if metaflac --list "$songfile" | grep -qEi 'album[[:space:]]*artist'; then continue; fi; IFS=/ read -r _ genre artist album disk song <<EOFn$songfilenEOFnecho metaflac --set-tag="ALBUMARTIST=$artist" "$songfile"; done` If the printed commands look correct, remove `echo` before `metaflac` and run it again to make the changes.
For a path shaped like `./Music/Genre/Artist/Album/Disk#/song.flac`, the artist is the fourth component from the end. Shell parameter expansion can peel off the final path components: remove the filename, disk, and album portions, then take the remaining basename. An `awk` alternative is `awk -F/ '{print $(NF-3)}'`, which extracts the artist directory directly from a path.

The path parsing works by repeatedly removing everything after the final slash. After removing the filename, disk directory, and album directory, the final remaining component is the artist name.