Recursively parse directory names and add a string if it is not found in the directory name

I would like to parse my FLAC music directory like this:

  • recursively check DIRECTORY names only
  • if the directory name does not contain the string "FLAC" or "flac", add " [FLAC]" at the end of the directory name.

This looks like it correctly finds the directories NOT containing the "FLAC" string:

find . -type d -not -iname '*flac*'

How can I then append " [FLAC]" to each of the directory names?

Asked By: Gianfranco


You could write a simple script to handle the direcrory names, and use find piped to xargs to feed the directory names to the script. Something like:

find . -type d -print0 | 
    xargs -0 $HOME/bin/waltscript

And do your checking and renaming in $HOME/bin/waltscript.

Answered By: waltinator

I’d try something like this

find . -depth -mindepth 1 -type d -not -iname '*flac*' -execdir echo mv -n -- '{}' '{} [FLAC]' ;

(remove the echo only after THOROUGH testing).

The -depth option specifies a depth first search, which avoids the case where it tries to rename a child whose ancestor has already been renamed. The -mindepth 1 stops it from trying to add [FLAC] to the current directory, .

The exact quoting of the replacement string is a matter of personal preference – ... {} {} [FLAC] or ... {} {}' [FLAC]' would work equally well.

Note that while GNU find replaces {} everywhere (not just where it occurs alone), other implementations might not – in that case you’d need to do something like

... -execdir sh -c 'for d; do echo mv -n -- "$d" "$d [FLAC]"; done' find-sh {} + 
Answered By: steeldriver
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.