I'm on a Macbook and would like to use bash to accomplish task.
Let's say I have a list of files in one directory like:
item1_2352352352.jpg
item2_2352352352.jpg
item3_2352352352.jpg
item3_2352352352.jpg
How can I sort and move these files to new folders with a bash one-liner? If not bash, python is OK too.
I'd like the folders to be named as item1, item2 etc. (everything before the first underscore).
CodePudding user response:
That would do the trick:
for i in item*_*; do folder=${i%_*}; mkdir -p "$folder"; mv -n "$i" "$folder"; done
Explanation:
for i in item*_*; do # for loop, loops over every file which fits the expression "item*_*" and puts current filename in $i
folder=${i%_*} # removes everything after a "_" from $i and saves the output to $folder
mkdir -p "$folder" # creates folder with content of $folder and without errors if directory exists (-p)
mv -n "$i" "$folder" # moves files without overwriting (-n)
done