Demand
The first two days encountered the need to extract files in a folder of about 10 levels, and then wrote this script.
A file structure such as the following:
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 is as follows:
#!/bin/Bash#desc:getfilefrom Directory#author: Ten years later Brother Lou (http://www.cnblogs.com/lurenjiashuo/)#example:SHGetfilefromdir.SHA Binit_path=${1%/}Save_path=${2%/}functionChecksavepath () {if[ -d $SAVE _path] Then RM-RF $SAVE _pathfi mkdir${save_path}Touch$SAVE _path". Log"}functionGetfilefromdir () { for file inch`ls$1` Do if[-D $1"/"$file ] ThenGetfilefromdir $1"/"$file ElseLocal 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 forSfolinch${init_path} DoGetfilefromdir ${sfol} Done
Run
sh getfilefromdir. SH dir1/dir2
The first parameter is the source folder, and the second is the target folder (you do not need to create it in advance).
If there is a file with the same name, there will be Dir2.log
The result is:
Dir2├──file1├──file2├──file3├──file4└──file5
This article from the ten years later Brother Lou blog (http://www.cnblogs.com/lurenjiashuo/), reproduced please specify the original address.
Shell script extracts files recursively from a folder