前兩天碰到需要在十層左右的文件夾中提取文件的需求,于是寫了此腳本。
如下面這樣的文件結構:
dir1 ├── a │ ├── b │ │ └── file1 │ └── file2 ├── c │ └── d │ ├── e │ │ └── file4 │ └── file3 └── file5
我們需要將其中的file1~file5提取出來放到另一個文件夾中。
腳本腳本getfilefromdir.sh如下:
#!/bin/bash#desc: get file from directory#author: 十年后的盧哥哥(http://www.CUOXin.com/lurenjiashuo/)#example: sh getfilefromdir.sh A BINIT_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 $1` do if [ -d $1"/"$file ] then getfilefromdir $1"/"$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}checksavepathfor sfol in ${INIT_PATH}do getfilefromdir ${sfol}done運行
sh getfilefromdir.sh dir1/ dir2
第一個參數是源文件夾,第二個是目地文件夾(不需要提前創建)。
如果有同名文件,會存在dir2.log中
結果為:
dir2├── file1├── file2├── file3├── file4└── file5
本文出自十年后的盧哥哥博客(http://www.CUOXin.com/lurenjiashuo/),轉載請注明原文地址。
新聞熱點
疑難解答