Using for loop to move files from subdirectories to parent directories

折月煮酒 提交于 2020-01-04 06:35:47

问题


I just made the switch to linux and I am trying to write my first bash script. I have a folder that contains numerous folders, all with subfolders containing files. Something like:

  • MainFolder

    • Folder1
      • Sub1 (Contains many files)
      • Sub2 (Contains many files)
    • Folder2
      • Sub1 (Contains many files)
      • Sub2 (Contains many files)

    . . .

I want to move all the files contained in the sub-folders to the their parent folders. My first instinct is to try and write a for-loop. I was able to do one folder at a time with the command:

mv MainFolder/Folder1/*/* MainFolder/Folder1/

But I was hoping to write a bash script to loop over all the folders in the main directory. Here is what I have so far:

#!/bin/bash

dir1="/pathto/MainFolder"

subs= ls $dir1

for i in $subs; do
  mv "$dir1/$i/*/*" "$dir1/$i/" 
done

This, obviously, does not work, but I do not understand where I am going wrong.

I also tried:

mv MainFolder/*/*/* MainFolder/*/

with pretty disastrous results. Once I get the file move working properly, I would also like to delete the old sub folders within the loop.


回答1:


Small change. change

subs=ls $dir1

to

subs=`ls $dir1`

Notice the backquotes. Backquotes actually execute the bash command and return the result. If you issue echo $subs after the line, you'll find that it correctly lists folder1, folder2.

Second small change is to remove double quotes in the mv command. Change them to

mv $dir1/$i/*/* $dir1/$i

Double quotes take literal file names while removing quotes takes the recursive directory pattern.

After that, your initial for loop is indeed correct. It will move everything from sub1 and sub2 to folder1 etc.




回答2:


!/bin/bash

dir1="/pathto/MainFolder"

subs=ls $dir1

for i in $subs; do

mv $dir1/$i// $dir1/$i

done



来源:https://stackoverflow.com/questions/22228718/using-for-loop-to-move-files-from-subdirectories-to-parent-directories

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