Tuesday, April 16, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  1] [ 0]  / answers: 1 / hits: 2755  / 2 Years ago, thu, december 2, 2021, 7:45:03

The goals is to move files out of the lowest level folder, back up one directory.



This does a great job but moves files higher up the folder hierarchy as well.



find . -name '*.jpg' -type f -execdir mv '{}' ../ ;


So if these jpgs were sat in a folder called 'photos', I want to move them up one level eg)




../




I've tried changing the '*.jpg' parameter to include the folder and tried using the folder instead of the dot after file. Also tried -maxdepth and -mindepth but they had no effect.



EDIT: This is for multiple folders i.e. it needs to recurse through an entire drive.


More From » bash

 Answers
2

Move files from the lowest sub directory up one level



The script below searches a directory for the lowest sub directory (= without sub directories) recursively and moves all found files in the folder(s) up one level, as literally asked for in The goals is to move files out of the lowest level folder, back up one directory:



#!/usr/bin/env python2
import shutil
import os
import sys

directory = sys.argv[1]

for root, dirs, files in os.walk(directory):
for dr in dirs:
dr = root+"/"+dr
# find folders without subfolders (= lowest level)
if len(next(os.walk(dr))[1]) == 0:
# direct superior directory
up = dr[:dr.rfind("/")]
# move files from lowest level one level up
for f in os.listdir(dr):
shutil.move(dr+"/"+f, up+"/"+f)


To use:




  1. Copy the script into an empty file, save it as reorganize.py

  2. Run it by the command:



    python /path/to/reorganize.py <directory_to_reorganize>


    If the name of your directory (to reorganize) contains spaces, use quotes:



    python /path/to/reorganize.py '<directory_to_reorganize>'






EDIT



As mentioned in a comment, with a little change, the script can be used to only move files from a folder name up one level. The moste efficient way is to do that directly after



for dr in dirs:


Then the script would be:



#!/usr/bin/env python3
import shutil
import os
import sys

directory = sys.argv[1]

for root, dirs, files in os.walk(directory):
for dr in dirs:
if dr == "<folder_name>":
dr = root+"/"+dr
# direct superior directory
up = dr[:dr.rfind("/")]
# move files from lowest level one level up
for f in os.listdir(dr):
shutil.move(dr+"/"+f, up+"/"+f)

[#19836] Thursday, December 2, 2021, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
fatuatexen

Total Points: 451
Total Questions: 107
Total Answers: 110

Location: Trinidad and Tobago
Member since Thu, Apr 27, 2023
1 Year ago
;