Recursively renaming folders and files to sub-directory name and moving files

柔情痞子 提交于 2019-12-12 01:23:23

问题


I have several sub-directories with no unanimous naming pattern within my home directory (for example ~/123, ~/456, ~/789).

Within each of these sub-directories, I have two folders named alignment1 and alignment2. In the folders alignment1 and alignment2 there are several files.

The files of interest to me are named alignment1 (no extension) in the alignment1 folder and the file alignment2 (no extension) in the alignment2 folder.

Please remember that in the folders alignment1 and alignment2 there are other files named alignment, but they have extensions (for example, alignment1.backbone, alignment1.bbcol and alignment2.backbone, alignment2.bbcol in respective alignment1 and alignment2 folders), but I am not interested in these files.

~/123/alignment1/alignment1
~/123/alignment2/alignment2
~/456/alignment1/alignment1
~/456/alignment2/alignment2
etc...

Question:

  1. My struggle is to rename the folders alignment1 and alignment2 to subdirectory_alignment1 and subdirectory_alignment2 (for example, 123_alignment1 and 123_alignment2).

  2. Then, in the folders alignment1 and alignment2, the alignment files, named alignment1 and alignment2 respectively, need to be renamed to subdirectory_1.aln and subdirectory_2.aln.

  3. Move the subdirectory_1.aln and subdirectory_2.aln to home directory.

I think it is closely related to this and this question, but I have been trying to amend the answers in the above postings for last few hours with no success.


回答1:


Trying to break the problem into small parts. This piece of code should find all occurences. Perhaps you should change something in the regex. \1 will match something that already matched inside \( and \). mindepth should find */*/* and below. The * is important here because of the number of / you will have on the result.

find * -mindepth 2 -type f | grep '/\([a-z]*[0-9]\)/\1' | while read f; do
  <process>
done

Now you are iterating all files of your interest. echo "$f" inside the loop is a nice idea before moving forward.

If the filter is working, below is some ideas to break the filename into small parts:

d1=`cut -d'/' -f1 <<< "$f"`
d2=`cut -d'/' -f2 <<< "$f"`
newName="${d1}/${d1}_${d2}"

Now just some simple mv "$from" "$to" here and there.



来源:https://stackoverflow.com/questions/35084642/recursively-renaming-folders-and-files-to-sub-directory-name-and-moving-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!