简体   繁体   中英

creating a unix script to sort and process files

Situation:

I have a folder on my desktop named unsorted_files which contains approximately 1GB of varying file types (jpg,gif,docx,png, wav,mid,csv) etc etc.

In addition to this, I have 3 further directories on the desktop that hold only their dedicated filetype (jpg,gif,docx).

The actual directory names for these dedicated directories are:

jpgdirectory
gifdirectory
docxdirectory 

Problem:

I would like to create a bash script that I can run through terminal on mac OS 10.10.5 that will separate and process these files types from the unsorted_files folder and place them into their newly created directories dependant on the file type.

ie. All jpg files in the folder unsorted_files upon the execution of the script will be sent to the jpgdirectory and all gif files will be dispatched to gifdirectory

The one caveat is, all file types out with (jpgdirectory, gifdirectory, docxdirectory) must be sent to miscellaneous

How could I achieve this objective from a bash script perspective or perhaps can this be done using solely terminal commands.

To automate a mkdir and mv command in bash, you could put this into a 'for' loop like the one below.

Code:

#!/bin/bash

unsorted_path="/path/to/unsorted/dir"
output_path="/path/to/output/dirs"
for type in $(cat filetypes.txt)
do
   mkdir -p ${output_path}/${type}directory
   mv ${unsorted_path}/*.${type} ${output_path}/${type}directory/
done

The 'filetypes.txt' file is a list of file types, one per line such as:

jpg
gif
docx
png
wav
mid
csv

You could also just hardcode the file types ie

#!/bin/bash

unsorted_path="/path/to/unsorted/dir"
output_path="/path/to/output/dirs"
for type in jpg gif docx png wav mid csv
do
   mkdir -p ${output_path}/${type}directory
   mv ${unsorted_path}/*.${type} ${output_path}/${type}directory/
done

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM