zoukankan      html  css  js  c++  java
  • 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/),转载请注明原文地址。

  • 相关阅读:
    sp_executesql是参数部分的长度定义发生变化能否重用执行计划
    scope_identity ident_current @@identity
    Useful undocumented extended stored procedures
    Delphi7对XML的支持分析
    Eclipse基础--Eclipse启动过程
    《现象七十二变》歌词
    被擦掉的名字
    同义词
    资产负债表的阅读与分析
    三谈多态——善用virtual
  • 原文地址:https://www.cnblogs.com/lurenjiashuo/p/get-file-from-dir.html
Copyright © 2011-2022 走看看