BASH SCRIPTING Theres a alot of files in a directory that we
BASH SCRIPTING
Theres a alot of files in a directory that we want to organize/put into other directories by year.
We are given the array
YEAR=(1990 1991 1992 1993 1994 1995 1996 1997 1998)
files look like somthing like this: skjdhflkdshfldksahfdsahlfk1990fjksdhlfk.pdf
after the scripts run this file should be put into the 1990/ directory
if the directory of the year does not exist, you should make it with mkdir, otherwise you should
not attempt to make the directory again
Solution
we can use the following construct of bash to solve the problem
Code
#declare an array of year
YEAR=(1990 1991 1992 1993 1994 1995 1996 1997 1998)
#iterate through all the files in the directory
for filename in *.*
do
#iterate through all element of year
for year in ${YEAR[*]}
do
#check if the filename contains any of the YEAR element as substring
if [[ $filename =~ $year ]]
then
#create directory if not existing
mkdir -p $year
#move the file to its required location
echo \"Moving file $filename to directory $year\"
mv $filename $year/
break
fi
done
done
