Wednesday, May 1, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  3] [ 0]  / answers: 1 / hits: 1538  / 2 Years ago, sun, july 3, 2022, 4:59:00

I know I can use something like mv *zip zip/ but I want to auto-create each folder if not exists and move my all files to them. With the below code I have to hard code everything. Is there any way to automate this. Like First Get all Extensions of files then Create folders if not exists and move files into them according to file types like png to images/png and mp3 to Audio/mp3 or pdf to Documents/pdf.


find . -name "*.mp4" -exec mv "{}" ./Videos ;

enter image description here


Edit-1
I have figured someway but I don't want to move .sh files how to delete from an array of a specific element and Group filetypes like png, jpg to images/png, images/jpg and mp3 to Audio/mp3 or pdf to Documents/pdf.


array=($(find . -type f | sed 's/.*.//' | sort | uniq ))

for dir in "${array[@]}"; do
[[ ! -d "$dir" ]] && mkdir "$dir"
find . -name "*.$dir" -exec mv "{}" ./"$dir" ;
done

More From » files

 Answers
0

Moving files based on file type

You can batch create your directories, move the files, then delete empty directories.


ScriptRoot='/some/path'

# Create the Directories
mkdir '${ScriptRoot}/Images'
mkdir '${ScriptRoot}/Music'
mkdir '${ScriptRoot}/Documents'
mkdir '${ScriptRoot}/Videos'

# Move the files (edit to match the targeted extensions...
find '${ScriptRoot}' -name '*.mp3' -or -name '*.flac' -exec mv {} '${ScriptRoot}/Music' ;
find '${ScriptRoot}' -name '*.jpeg' -or -name '*.jpg' -or -name '*.png' -exec mv {} '${ScriptRoot}/Images' ;
# find (... and so and so for Documents and Videos)

# Delete empty directories
find '${ScriptRoot}' -depth -type d -empty -exec rmdir {} ;

Moving files based on file extension is way simpler but that is not what was asked.

To achieve what described, this can be modified with a file list generated by find, looped with a while read and several tests on file ext for moving to directories


for filename in *; do
if [[ -f "$filename" ]]; then
ext=${filename#$base.}
mkdir -p "${ext}"
mv "$filename" "${ext}"
fi
done

[#2950] Tuesday, July 5, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
fatuatexen

Total Points: 451
Total Questions: 107
Total Answers: 110

Location: Trinidad and Tobago
Member since Thu, Apr 27, 2023
1 Year ago
;