为目录中的所有文件(递归地)创建符号链接到其他目录

时间:2017-01-17 22:10:39

标签: ruby linux bash

我在文件夹中有文件:

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

我需要将.txt文件的符号链接到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

2 个答案:

答案 0 :(得分:1)

在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

导致

.
├── 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

答案 1 :(得分:0)

可以使用ruby脚本执行此操作:

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