简体   繁体   中英

Make symlinks for all files in directory (recursively) into other directory

I have files in folder:

folder_a/
  subfolder_1/
    file.txt
  subfolder_2/
    subfolder_3
      file2.txt
  file3.txt

I need to get symlinks to .txt-files into folder_b :

folder_b/
  000_file.txt  ---> folder_a/subfolder_1/file.txt
  001_file2.txt ---> folder_a/subfolder_2/subfolder_3/file2.txt
  003_file3.txt ---> folder_a/file3.txt

In Bash:

shopt -s globstar                    # Enable **/* glob

for fname in folder_a/**/*.txt; do   # Get all .txt in folder_a
    bname=${fname##*/}               # Basename of link target

    # Assemble link name
    printf -v lname '%s%03d%s' 'folder_b/' "${bname//[!0-9]}" "_$bname"

    # Create link
    ln -s "$fname" "$lname"
done

resulting in

.
├── folder_a
│   ├── file3.txt
│   ├── subfolder_1
│   │   └── file.txt
│   └── subfolder_2
│       └── subfolder_3
│           └── file2.txt
└── folder_b
    ├── 000_file.txt -> folder_a/subfolder_1/file.txt
    ├── 002_file2.txt -> folder_a/subfolder_2/subfolder_3/file2.txt
    └── 003_file3.txt -> folder_a/file3.txt

Can do this with ruby script:

src = '/path/to/folder_a/'
dst = '/path/to/folder_b/'

files = `find $(realpath #{src}) -type f -iname "*.txt"`.split("\n")
files.each_with_index do |path, idx|
  name = File.basename path
  `ln -s "#{path}" "#{dst + "%03d" % idx}__#{name}"`
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM