递归地将目录名添加到文件名

Cat*_*sel 5 files rename

鉴于以下结构:

source/
  dir1/
   file1.ext1
   file2.ext2
  dir2/
   file3.ext3
    dir3/
     file4.ext4
Run Code Online (Sandbox Code Playgroud)

我想实现以下目标:

destination/
 dir1file1.ext1
 dir1file2.ext2
 dir2file3.ext3
 dir3file4.ext4
Run Code Online (Sandbox Code Playgroud)

换句话说,我想递归地将所有文件从源移动到目标,将原始子目录名称附加到文件名。

mur*_*uru 6

使用 Perl 重命名和find

$ find source -type f | rename -n 's:(^|.*/)([^/]*)/([^/]*)$:destination/$2$3:'
rename(source/dir2/file3.ext3, destination/dir2file3.ext3)
rename(source/dir2/dir3/file4.ext4, destination/dir3file4.ext4)
rename(source/dir1/file1.ext1, destination/dir1file1.ext1)
rename(source/dir1/file2.ext2, destination/dir1file2.ext2)
Run Code Online (Sandbox Code Playgroud)

正则表达式(^|.*/)([^/]*)/([^/]*)将路径的最后两个组件(文件名和父目录)保存为第二个和第三个匹配组。

destination在运行此目录之前,该目录必须存在。该-n是进行测试,将其拆下进行实际移动文件。