如何仅删除目录的内容?


14

我在一个文件夹中:/var/myfolder

里面还有一些其他文件夹,例如:/var/myfolder/A/ /var/myfolder/B/ `/var/myfolder/C/etc。

每个文件中都有一些带有随机名称的文件。如何从内部所有文件夹中删除所有文件/var/myfolder

结构(内部的所有目录,例如A,B,C等/var/myfolder)应保持完整。

Answers:


17

尝试:

find /var/myfolder -type f -delete

这会将所有常规文件放在/ var / myfolder下,并将其删除,仅保留目录。


感谢您的解决方案。我应该提到在Solaris 9中正在执行此操作,因此我发现没有-delete选项,但这是一个很好的起点。
IroeN 2012年

2
我能够提出以下解决方案:find / var / myfolder -type f -exec rm -f {} \;
IroeN 2012年

2
抱歉。我使用Debian或Ubuntu。据我所知,您的解决方案是等效的。
StarNamer 2012年

6
-type f!=! -type d
mikeserv '16

7

对于zsh,请使用. glob限定符仅匹配常规文件:

rm -- **/*(.)

这将递归删除当前目录及其子目录中的所有(非隐藏)常规文件。添加Dglob限定符也可以删除隐藏的常规文件(以及隐藏目录中的常规文件)。


我正在使用bash。
IroeN 2012年

1
@ user6554:...您的问题或使用的标签均未指示;)
0xC0000022L 2014年


3
find . -depth -exec rm {} + 2>/dev/null

rm 不会删除目录-因此只需在所有内容上运行它即可。

要保留目录的符号链接:

find .  ! -type d -exec sh -c '
    for f do [ -d  "$f" ] || 
          set "$@" "$f";  shift
    done; rm  "$@"' sh  {} +

我认为,如果有很多文件需要在上述版本中进行测试,那么这也许也可以以一种稍微优化的方式工作:

find . ! \( -type l -o -type d \)  \
-exec  rm {} + -o -exec  sh -c '
       for f do [ -d "$f" ] ||
       unlink "$f";done' sh {} +

请注意,GNU 为此find提供了一个-xtype选项。
斯特凡Chazelas

@StéphaneChazelas-ast也是如此。但我认为,我根本不需要深度。我把它放在最前面,以避免出现太多错误调用-是否保持沉默-但在其他情况中却很愚蠢。
mikeserv '16

1
# This will delete all directory contents, including hidden files and
# subdirectories, without deleting the directory itself

# With GNU find:
find /path/to/directoryToEmpty -mindepth 1 -delete

# OpenBSD (and probably other BSDs)
find /path/to/directoryToEmpty -mindepth 1 -depth -exec rm -f {} \;

# To see what it deletes, in the order it will delete it:
find /path/to/directoryToEmpty -mindepth 1 -depth -print

0
rm var/myfolder/*/*

会删除子文件夹中的所有内容,而不会碰到子文件夹本身。

首先*是对的子目录myfolder本身(AB,...)。第二个*是针对中的文件AB等等。

如果有更多的内部文件夹AB等首先运行: rm /var/myfolder/*/*/*然后运行rm /var/myfolder/*/*


0

您还应该能够将cd转到有问题的目录树的顶部,然后运行:

find . -type f -print0 | xargs -0 rm -rf

并且应该删除所有文件,同时保持目录树完整。如果您确信没有包含空格的任何文件或目录名称,则可以忽略-print0和-0选项。

find命令可区分文件(-type f)和链接(-type l),因此应保留链接(如果有)完整。虽然没有测试。如有疑问,请运行:

找 。型l

并在运行之前的find命令之前查看是否有任何显示。


您能解释一下rm国旗如何-r, -R, --recursive - remove directories and their contents recursively适应吗?
斯蒂芬·劳奇

因为我们没有运行rm -rf,所以我们正在运行find。键入f,然后将其输出传递给rm -rf。因此,它仅删除文件,而不涉及目录。那就是| xargs位确实如此,它从左侧的命令获取输出,并将其发送到右侧的命令。
rjh427

完全是我的意思。如果您不传递任何目录,那么仅在目录上起作用的标志有什么用?
斯蒂芬·劳奇

因为肌肉记忆力仍然有效。您可以对-f“ force”选项提出相同的反对意见,我将给您相同的答案。
rjh427

-2

只需使用以下命令:

sudo rm -rf directory_in_which_you_have_content / *

- - - - - - - - 要么 - - - - - - - - - - - - - - - - - -----------------------

“ *”代表所有内容,因此当您使用*时,它将删除所有内容。因此,请使用以下命令或转到要删除所有内容的目录,然后使用以下命令:

须藤rm -rf *

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.