So, i create a bash script that search recursively for files that includes the words that you introduce, then creates a folder (if the folder does not exist) with the same name as the variable introduced and finally it copies all the files that meet the word in that new folder.
So for example, if i have a folder named "files_1906" and inside i have a file named "hello_1906.pdf" and then another folder (not inside the first) named "hello" and inside a file named "1906hello" and if i introduce: .sh program_name.sh "1906" it should create a folder named 1906 and copy the two files inside.
but right now i only managed to create the folders, it doesn't copy the files.
here is the full code:
#!/bin/bash
currentDir=$(pwd)
for var in "$@"
do
countCurrentWord=$(find . -type f -name "$var" | grep "$var" | wc -l)
echo -e "$countCurrentWord"
echo -e "Number of files matching the keyword $var: $countCurrentWord"
if [[ $countCurrentWord -gt 0 ]]
then
if [[ -d $currentDir/$var ]]
then
echo -e "the folder $var already exists, copying the files...\n"
else
mkdir "$currentDir"/"$var"
echo -e "the folder $var does not exist, creating the folder and copying the files...\n"
fi
IFS=$'\n'
array=$(find . -type f -name "$var")
declare -p array > /dev/null 2>&1
declare -a array > /dev/null 2>&1
length=${#array[@]}
for ((i=0; i < length; i++))
do
cp "${array[i]}" "$currentDir"/"$var"/ > /dev/null 2>&1
echo -e "hello world"
done
else
echo -e "no files found, no move will be made.\n"
fi
done
the console returns the following:
first it says that $countCurrentWord = 0, which doesn't make any sense cause there are files that contains "1906"
but here is where this get's trippy:
the program ignores the greater than 0 and starts the loop, creating the folder called 1906, but after, it doesn't copy the file, it remains empty once is created. I get also the hello world from the second loop.
So, how can we fix this so that it does its job and copies the files?
i already tried with files named only "1906" (also does not work), but the script should be capable of reading the full name of a file and discern if contains the keyword introduced. i don't know if i have a typo or anything, i'm not experienced in scripting in bash
I hope i explained this well enough so you guys can help me, thank you for your effort!