Delete all files but keep all directories in a bash script?

前端 未结 4 989
眼角桃花
眼角桃花 2021-01-30 23:31

I\'m trying to do something which is probably very simple, I have a directory structure such as:

dir/
    subdir1/
    subdir2/
        file1
        file2
              


        
相关标签:
4条回答
  • 2021-01-30 23:46
    find dir -type f -exec rm {} \;
    

    where dir is the top level of where you want to delete files from

    Note that this will only delete regular files, not symlinks, not devices, etc. If you want to delete everything except directories, use

    find dir -not -type d -exec rm {} \;
    
    0 讨论(0)
  • 2021-01-30 23:49
    find dir -type f -exec rm '{}' +
    
    0 讨论(0)
  • 2021-01-30 23:51

    With GNU's find you can use the -delete action:

    find dir -type f -delete
    

    With standard find you can use -exec rm:

    find dir -type f -exec rm {} +
    
    0 讨论(0)
  • 2021-01-31 00:05
    find dir -type f -print0 | xargs -0 rm
    

    find lists all files that match certain expression in a given directory, recursively. -type f matches regular files. -print0 is for printing out names using \0 as delimiter (as any other character, including \n, might be in a path name). xargs is for gathering the file names from standard input and putting them as a parameters. -0 is to make sure xargs will understand the \0 delimiter.

    xargs is wise enough to call rm multiple times if the parameter list would get too big. So it is much better than trying to call sth. like rm $((find ...). Also it much faster than calling rm for each file by itself, like find ... -exec rm \{\}.

    0 讨论(0)
提交回复
热议问题