0

Based on this question,

How to delete directories based on `find` output?

I tried to remove only the first folder of result doing:

find * -type d | head -n1 | -exec rm -rf {} \;

But I receive this error:

bash: -exec: command not found

What's wrong?

3

You can use -quit after using -delete or -exec:

-quit
Exit immediately. No child processes will be left running, but no more paths specified on the command line will be processed.


Deleting the first result of your find command:

find * -type d -exec rm -Rf {} \; -quit

or

find . ! -path . -type d -exec rm -Rf {} \; -quit

The latter will find hidden folders.


Note, that your find output may not be sorted alphabetically.

For deletion of first result afer sorting:

find * -maxdepth 1 -type d -print0 | sort -z | head -zn1 | xargs -r0 rm -Rf

For numeric sort, use sort -zn.

| improve this answer | |
  • Thanks a lot! so I'll add "sort -z", but I'll have the same problem of | head -n1, isn't it? – Ponzio Pilato Jan 21 '19 at 14:33
0

This seems very dangerous but you could try:

find * -type d | head -n1 | xargs rm -rf
| improve this answer | |
  • 1
    Indeed dangerous. Having>$ ls: important_file important_file\nfake_folder, your command will delete very_important_file. Better use find -print0 and head -z and xargs -0. – pLumo Jan 21 '19 at 14:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.