使用for循环将文件从子目录移动到父目录 [英] Using for loop to move files from subdirectories to parent directories

查看:412
本文介绍了使用for循环将文件从子目录移动到父目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是做了切换到Linux,我想写我的第一个bash脚本。我有一个包含众多文件夹的文件夹,所有文件夹都包含子文件夹。例如:


  • MainFolder


    • Folder1

      • Sub1(包含多个文件)
      • Sub2(包含多个文件)
      (包含许多文件)

    • 文件夹2

      • Sub2(包含许多文件)









我想将子文件夹中包含的所有文件移动到其父文件夹。我的第一本能是尝试写一个for循环。我可以一次执行一个文件夹:

$ m $ MainFolder / Folder1 / * / * MainFolder / Folder1 /

但是我希望编写一个bash脚本来遍历主目录中的所有文件夹。这是我到目前为止:

 #!/ bin / bash 

dir1 =/ pathto / MainFolder

subs = ls $ dir1

for $ in $ subs;做
mv$ dir1 / $ i / * / *$ dir1 / $ i /
完成

这显然不起作用,但是我不明白我错在哪里。



我也试过:

$ p $ m $ MainFolder / * / * / * MainFolder / * /

具有相当不幸的结果。一旦我的文件移动工作正常,我也想删除循环内的旧子文件夹。 解决方案

。改变

  subs = ls $ dir1 

  subs =`ls $ dir1` 

注意反引号。反引号实际上执行bash命令并返回结果。如果你在这行之后发行 echo $ subs ,你会发现它正确地列出了 folder1 文件夹2

第二个小改动是删除 mv 命令中的双引号。将它们改为

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

双引号需要文字文件名,而删除引号需要递归目录模式。



之后,你的初始循环确实是正确的。它将把所有内容从 sub1 sub2 移动到 folder1 等。


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.

解决方案

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.

这篇关于使用for循环将文件从子目录移动到父目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆