LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   move files or a directory to another directory using shell script (https://www.linuxquestions.org/questions/linux-newbie-8/move-files-or-a-directory-to-another-directory-using-shell-script-4175484563/)

user1111 11-14-2013 08:22 AM

move files or a directory to another directory using shell script
 
Hi all,
I need help in moving a file to a different folder using k-shell script. I am doing a file pattern search in a directory (two levels deep), and if found need to move that file to a different folder.

For eg.
input_dir = /opt/oracle/client1/
searching in /opt/oracle/client1/test1/work/
All the files with ".done" extension need to be moved to /opt/oracle/client1/test1/Done folder.
This is what I have so far

find "$input_dir" -type f -mindepth 3 -maxdepth 3 | while read filename;
do
#echo "$filename"
echo "$filename" | grep -q '.done' && echo "$filename is done".
done.

I don't know how I can move the file to the folder when I don't have a folder name. Thanks for the help.

suicidaleggroll 11-14-2013 08:27 AM

How about
Code:

input_dir=/opt/oracle/client1
output_dir=Done
for i in $input_dir/*/*/*.done; do
  loc=$(dirname "$i")
  dest=$(dirname "$loc")/$output_dir
  if [[ ! -d "$output_dir" ]]; then
      mkdir -p "$output_dir"
  fi
  mv "$i" "$output_dir"
done


user1111 11-14-2013 08:41 AM

Thanks for the quick reply. The only problem is that I have multiple folders in client which I forgot to mention in the original question.
Eg - /opt/oracle/client1/test1/A - file needs to be moved to opt/oracle/client1/test1/Done
/opt/oracle/client1/test2/A - file needs to be moved to opt/oracle/client1/test2/Done
/opt/oracle/client1/test3/A - file needs to be moved to opt/oracle/client1/test3/Done

Also, is there a way to detect if the file at that level is a file or a folder. If it is a folder, then the folder needs to be moved since it would have ".done" extension.

suicidaleggroll 11-14-2013 09:02 AM

I edited my code before you posted to dynamically build up the destination, it should take care of your first problem.

As for the file or directory, you can use the -f or -d checks, but it shouldn't matter, the above code should work regardless of the type.

user1111 11-15-2013 12:03 AM

It worked like a charm. Thanks!
If I also have to move the .NOTDONE files/folders to a NOTDONE folder, then should I write another similar loop or can it be taken care of in the same loop.

Thanks for all the help!

user1111 11-15-2013 04:59 AM

I encountered an issue with this when I run it again. It is searching in the "Done" folder. Can we somehow exclude this folder in the search ?

Thanks!

suicidaleggroll 11-15-2013 08:13 AM

You could check if loc and output dir are the same before the move, should handle any files already in "Done".


All times are GMT -5. The time now is 05:10 AM.