Ubuntu – How to delete all folders of a specific name without deleting Contents in it

bashcommand linedeletedirectory

How do I delete all Folders with a specific name (e.g. 128Kbps_Songs) without deleting its files

For example if I have directory "MP3_SONGS" with subdirectories "A", "B", "C" and each subdirectory has MANY directory Contains Film Name "FILM_NAME1", "FILM_NAME2", "FILM_NAME3" in it, In That Each Film NAme I have specific Folder NAme (128Kbps_Songs) in this "128Kbps_Songs" Folder I have That Film mp3 Songs Files

how can I remove the Folder "128Kbps_Songs", in Each Film_Name directory and Have to get these mp3 songs in that FILM_NAME.. ( Have to Delete 128Kbps_Songs Folder in all FILM_NAME without deleting the mp3 Songs in it, have to get the mp3 in FILM_NAME Directory..

MP3_SONGS (Parent Directory) ------ A , B, C

A (Sub Directory1) ------ FILM_NAME1 , FILM_NAME2
B (Sub Directory2) ------ FILM_NAME3 , FILM_NAME4
c (Sub Directory3) ------ FILM_NAME5 , FILM_NAME6

FILM_NAME1 (Directory) ---- 128Kbps_Songs (Directory) ------ FILM_NAME1 (MP3 Files)
FILM_NAME2 (Directory) ---- 128Kbps_Songs (Directory) ------ FILM_NAME2 (MP3 Files)

FILM_NAME3 (Directory) ---- 128Kbps_Songs (Directory) ------ FILM_NAME3 (MP3 Files)
FILM_NAME4 (Directory) ---- 128Kbps_Songs (Directory) ------ FILM_NAME4 (MP3 Files)

FILM_NAME5 (Directory) ---- 128Kbps_Songs (Directory) ------ FILM_NAME5 (MP3 Files)
FILM_NAME6 (Directory) ---- 128Kbps_Songs (Directory) ------ FILM_NAME6 (MP3 Files)

Need Files in:
FILM_NAME1 (Directory)  ------ FILM_NAME1 (MP3 Files)
FILM_NAME2 (Directory)  ------ FILM_NAME2 (MP3 Files)

FILM_NAME3 (Directory)  ------ FILM_NAME3 (MP3 Files)
FILM_NAME4 (Directory)  ------ FILM_NAME4 (MP3 Files)

FILM_NAME5 (Directory)  ------ FILM_NAME5 (MP3 Files)
FILM_NAME6 (Directory)  ------ FILM_NAME6 (MP3 Files)

Best Answer

Create a simple script with following contents

#!/bin/bash

while IFS= read -r -d '' n; 
do   
   dir=$(dirname "$n") ; 
   mv "${n}"/* "${dir}"
   rmdir "${n}"
done < <(find -type d -name "128Kbps_Songs" -print0)

Save it and make it executable using chmod +x your_script

Now run it using ./your_script


Here IFS= is done to preserve the space in the filename or path.

  • -r - disables interpretion of backslash escapes and line-continuation in the read data.

  • -d - recognize delimiter as data-end. Here it is emptying out the IFS

  • dirname is use to remove the last folder name i.e 128Kbps_Songs from the find command output. (from ./temp/MP3_SONGS/128Kbps_Songs to ./temp/MP3_SONGS)