mac OS – Creating folders based on part of a filename

前端 未结 2 400
北荒
北荒 2021-01-15 00:31

I\'m running macOS and looking for a way to quickly sort thousands of jpg files. I need to create folders based on part of filenames and then move those files into it.

2条回答
  •  盖世英雄少女心
    2021-01-15 01:13

    Using find with bash Parameter Substitution in Terminal would likely work:

    find . -type f -name "*jpg" -maxdepth 1 -exec bash -c 'mkdir -p "${0%%_*}"' {} \; \
    -exec bash -c 'mv "$0" "${0%%_*}"' {} \;
    

    This uses bash Parameter Substitution with find to recursively create directories (if they don't already exist) using the prefix of any filenames matching jpg. It takes the characters before the first underscore (_), then moves the matching files into the appropriate directory. To use the command simply cd into the directory you would like to organize. Keep in mind that without using the maxdepth option running the command multiple times can produce more folders; limit the "depth" at which the command can operate using the maxdepth option.

    ${parameter%word}
    ${parameter%%word}
    

    The word is expanded to produce a pattern just as in filename expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted.

    ↳ GNU Bash : Shell Parameter Expansion

提交回复
热议问题