1

I would like to remove the whole content of a folder, apart from one file. The problem is can't copy the file to another folder and then back to the first folder, because then the application doesn't accepts the file, so the one file must stay in the folder.

Exists there a command like I described?

4

I would go about it like this:

find . ! -name <filename> -delete

for this to work with folders, you have to replace the delete with an exec rm -r

find . ! -name <filename> -exec rm -rv {} \;

This breaks down to

find = find

. = in current working directory, you can replace . with a path, like ~/Documents/

! = not

-name = name

<filename> = file

-exec = execute

rm -rv = verbose remove

{} = results of the find

\; = close the execution

Find all files and folders in your working folder, that do not have the name filename and then execute the remove command on the results.

You should do a dry run without the delete option, first:

find . ! -name <filename>

This command gives you a list of all files and folders in your working directory that are not named <filename>. Adding -delete or -exec rm -rv {} \;, will delete this files and folder (the exec version).


You could also use

rm -v [^filename]

for folders add -r

rm -rv [^filename]

Somehow I feel more comfortable using the find option. Mainly because you can do a dry run. Either way I would start with a dummy folder and try both options.

3
  • Works that version also with folders? EDIT: With find . ! -name <filename> I'm getting a long list in Terminal. – user121028 Jul 6 '15 at 8:39
  • find . ! -name <filename> gives you all files (and folders) in your current folder. As about deletion of folders: I changed my answer to also delete folders. – Volsk Jul 6 '15 at 8:44
  • The surroundings changed ... Now I'm having a folder and their content must stay. Is that possible with find? – user121028 Jul 6 '15 at 17:52
0

For being really sure about this, you could use find to create a deletion shellscript with "rm" commands:

find . ! -name "<filename>" -exec echo "rm -rf {}" >> /tmp/rm.sh \;

Delete every line in the shellscript /tmp/rm.sh you do not like, then execute it by

bash /tmp/rm.sh

But be careful - find also finds directories and "rm -rf" would then delete them recursively as well! Narrow down your search by telling find the filetype to search for:

find . ! -name "<filename>" -type <filetype> -exec echo "rm -rf {}" >> /tmp/rm.sh \;

Have fun! :-)

3
  • Is there a way to add a path to the command line so that I get only results from the path? – user121028 Jul 6 '15 at 8:42
  • Replace the "." with your path. find <your path> ! -name "<filename>" -type <filetype> -exec echo "rm -rf {}" >> /tmp/rm.sh \; – Martin Allert Jul 6 '15 at 11:36
  • Is it easier with ls? If I copy the files with cp the files are outside of their folders. – user121028 Jul 7 '15 at 9:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .