Skip to content

Instantly share code, notes, and snippets.

@ErykDarnowski
Last active September 11, 2023 12:29
Show Gist options
  • Save ErykDarnowski/bbf8da81ee4ed878912d89b822f6e493 to your computer and use it in GitHub Desktop.
Save ErykDarnowski/bbf8da81ee4ed878912d89b822f6e493 to your computer and use it in GitHub Desktop.
Rename all dirs that contain more than 1 file from `Emulator` to `Emulators` (without `rename` command)

Rename all dirs that contain more than 1 file from Emulator to Emulators (without rename command)

find -type d -name "*Emulator" -not -empty -not -path "*Games*" -exec sh -c 'echo "{}: $(ls "{}" | wc -l)"' \; | awk -F: '$2 > 1' | cut -d: -f1 | xargs -I {} sh -c 'mv "{}" "{}s"'

The command is composed of several parts, each separated by a pipe (|) symbol. The pipe symbol means that the output of the previous part is passed as the input to the next part.

The first part is:

find -type d -name "*Emulator" -not -empty -not -path "*Games*" -exec sh -c 'echo "{}: $(ls "{}" | wc -l)"' \;

This part uses the find command to search for directories (-type d) that have the word Emulator in their name (-name "*Emulator") and are not empty (-not -empty) and do not have the word Games in their path (-not -path "*Games*"). For each directory that matches these criteria, the -exec option executes a shell command (sh -c) that prints out the directory name (echo "{}") followed by a colon (:) and the number of files in that directory ($(ls "{}" | wc -l)). The \; at the end is needed to terminate the -exec option.

The second part is:

awk -F: '$2 > 1'

This part uses the awk command to filter out the output of the previous part. The -F: option tells awk to use the colon (:) as the field separator. The $2 > 1 condition tells awk to print only the lines where the second field (the number of files) is greater than 1.

The third part is:

cut -d: -f1

This part uses the cut command to extract only the first field (the directory name) from the output of the previous part. The -d: option tells cut to use the colon (:) as the delimiter. The -f1 option tells cut to print only the first field.

The fourth part is:

xargs -I {} sh -c 'mv "{}" "{}s"'

This part uses the xargs command to execute another shell command (sh -c) for each line of input from the previous part. The -I {} option tells xargs to replace each occurrence of {} with the input line. The shell command that is executed is mv "{}" "{}s" which moves (renames) each directory by appending an s to its name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment