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

  • 相关阅读:
    javaweb中带标签体的自定义标签
    javaweb带父标签的自定义标签
    Filter的常见应用
    Filter内容
    JFace TableViewer性能改善 -- 使用VirtualTable
    SWT table性能改善 -- 使用VirtualTable
    java自动探测文件的字符编码
    [小技巧]Filezilla无法确定拖放操作目标,由于shell未正确安装__解决办法
    批量导出VBA工程中的Source
    开源许可证知多少
  • 原文地址:https://www.cnblogs.com/lurenjiashuo/p/get-file-from-dir.html
Copyright © 2011-2022 走看看