shell脚本从文件夹中递归提取文件

需求

前两天碰到需要在十层左右的文件夹中提取文件的需求,于是写了此脚本。

如下面这样的文件结构:

    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.cnblogs.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.cnblogs.com/lurenjiashuo/),转载请注明原文地址。

shell脚本从文件夹中递归提取文件

相关文章:

你感兴趣的文章:

标签云: