Shell scripts recursively Extract files from folders,

Source: Internet
Author: User

Shell scripts recursively Extract files from folders,

Two days ago, I ran into the need to extract files from a folder around 10 layers, so I wrote this script.

The file structure is as follows:

    dir1    ├── a    │   ├── b    │   │   └── file1    │   └── file2    ├── c    │   └── d    │       ├── e    │       │   └── file4    │       └── file3    └── file5

We need ~ File5 is extracted and put into another folder.


The script getfilefromdir. sh is as follows:

#! /Bin/bash # desc: get file from directory # author: a decade later, Lu brother ( # 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/$ fi Le "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 done} checksavepathfor sfol in $ {INIT_PATH} do getfilefromdir $ {sfol} done
sh dir1/ dir2

The first parameter is the source folder, and the second parameter is the destination folder (you do not need to create it in advance ).

If a file with the same name exists, it will exist in dir2.log.


dir2├── file1├── file2├── file3├── file4└── file5

This article from ten years later brother Lu blog (, reprint please indicate the original address.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.