简体   繁体   English

在Linux中相应目录内的文件中添加每个目录的名称

[英]Add name of each directory to files inside the corresponding directory in linux

I have a directory containing multiple directories. 我有一个包含多个目录的目录。 here is an example of the list of directories: 这是目录列表的示例:

  • dir1_out dir1_out
  • dir2_out dir2_out
  • dir3_out dir3_out
  • dir4_out dir4_out

Each directory contains multiple files. 每个目录包含多个文件。 For example folder1_out contains the following files: 例如,folder1_out包含以下文件:

  • file1 文件1
  • file2 文件2
  • file3 文件3

In the same fashion other directories contain several folders. 其他目录以相同的方式包含多个文件夹。 I would like to add the name of each directory to file name in the corresponding directory. 我想将每个目录的名称添加到相应目录中的文件名中。 I would like to have the following result in first directory(dir1_out): 我想在第一个目录(dir1_out)中得到以下结果:

  dir1.file1
  dir1.file2
  dir1.file3

Since I have around 50 directories I would like to write a loop that takes the name of each directory and add the name to the beginning of all subfiles. 由于我有大约50个目录,因此我想编写一个循环,该循环采用每个目录的名称,并将名称添加到所有子文件的开头。

Do you have any idea how can I do that in linux. 你有什么主意,我怎么能在Linux中做到这一点。

A simple bash onliner if there aren't too many files is: 如果文件太多,一个简单的bash onliner是:

for p in */*; do [ -f "$p" ] && mv -i "$p" "${p%/*}/${p/\//.}"; done

This uses parameter expansions to generate new filenames, after checking that we are trying to rename an actual file - See bash manpage descriptions of ${parameter%word} and ${parameter/pattern/string} 在检查我们试图重命名实际文件后,它使用参数扩展来生成新的文件名-请参见${parameter%word}${parameter/pattern/string} bash联机帮助说明。

If there may be too many files to safely expand them all into a single list: 如果文件太多,无法安全地将它们全部扩展到一个列表中:

#!/bin/bash
find . -maxdepth 2 -print |\
while read p; do
    p="${p#./}"
    mv -i "$p" "${p%/*}/${p/\//.}"
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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