Demand
I wrote this script two days ago when I met the need to extract a file in a 10-story folder.
A file structure like the following:
Copy Code code as follows:
Dir1
├──a
│├──b
││└──file1
│└──file2
├──c
│└──d
│├──e
││└──file4
│└──file3
└──file5
We need to extract the file1~file5 and put it in another folder.
Script
The script getfilefromdir.sh as follows:
Copy Code code as follows:
#!/bin/bash
#desc: Get file from directory
#example: sh getfilefromdir.sh A B
init_path=${1%/}
save_path=${2%/}
function Checksavepath () {
If [-D $SAVE _path]
Then
RM-RF $SAVE _path
Fi
mkdir ${save_path}
Touch $SAVE _path ". Log"
}
function Getfilefromdir () {
For file in ' ls $ '
Todo
If [-D $/$file]
Then
Getfilefromdir "/" $file
Else
Local path= "$1/$file"
Local name= $file
if [!-F $SAVE _path "/" $name]
Then
echo "CP ${path} to ${save_path}/${name}"
CP ${path} "${save_path}/${name}"
Else
echo "${path} file already exists"
echo "${path}" >> $SAVE _path ". Log" 2>&1
Fi
Fi
Done
}
Checksavepath
For Sfol in ${init_path}
Todo
Getfilefromdir ${sfol}
Done
Run
Copy Code code as follows:
SH getfilefromdir.sh dir1/dir2
The first parameter is the source folder, and the second is the target folder (no need to create in advance).
If there is a file with the same name, there will be a dir2.log
The results are:
Copy Code code as follows:
Dir2
├──file1
├──file2
├──file3
├──file4
└──file5