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 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 $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
}

checksavepath

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

转载于:https://www.cnblogs.com/lurenjiashuo/p/get-file-from-dir.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值