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
)
In these situations there is a risk of files with the same name being overwritten. As mentioned by @Arronical, you can avoid this using the -b
flag to mv
which causes any identically named files to be differentiated by appending ~
to their names. However, if there are three or more files with the same name, only the first and last will be saved, so check the contents before moving to protect your files.
The first, simple case is easy; we can use a shell glob. However, this won't move hidden files, so if you have any filenames beginning with .
, start by turning on dotglob
shopt -s dotglob
Then you can run:
mv -b /home/smit/test/* /home/smit
rmdir /home/smit/test
Turn off dotglob
if you like (it will return to default anyway when you open a new shell):
shopt -u dotglob
For the second (real) case, we will use find
, which moves hidden files by default:
Make sure you are in the right location first.
cd /usr/share/background/all
find -type f -exec echo mv -vb -- {} . \;
If that looks good, run it without echo
to actually move files
find -type f -exec mv -vb -- {} . \;
Then find the directories
find -type d
If you see what you want to remove:
find -type d -delete
This is safe since it will refuse to remove directories that still have contents.
Best Answer
To remove everything in a directory without removing the directory, type in:
Please note, the
/*
part is very important. If you put a space before the*
, it will delete all your files in your current directory.Also, be very careful playing with
rm
,-r
and*
all in the same command. They can be a disastrous combination.Update: Okay, I realized if you do have hidden/dot files [filenames with dots at the beginning, e.x.
.hidden
] then this will leave those files intact.So really, the simplest solution to the original question is:
Another one would be to use
find
's-exec
option or pipe toxargs
(below):