Delete nested hidden files with egrep and xargs

大兔子大兔子 提交于 2019-12-08 04:29:56

问题


I'm trying to remove all directories and files that are hidden and recursively remove them. the only hidden directories at current directory level are . and .. but each of several directories has several hidden files (begin with ._) within them. ls -aR | egrep '^\.\w+' | will list out all the files I want easy enough, but adding '| xargs 'rm'` gives me the rm error "No such file or directory".

I take this to mean that each directory I'm trying to remove needs to be appended with it's parent directory and /. But maybe I'm wrong.

How can I update this command to delete these files?


回答1:


Use find:

find . -type f -name .\* -exec rm -rf {} \;

The -exec is white-space safe: {} will pass the file path (relative to .) as a single argument to rm.

Better is this:

find . -name .\* -delete

(with thanks to @John1024). The first form spawns a process for each file found, whereas the second form does not.

xargs by default is not white-space safe:

$ touch a\ b
$ find . -maxdepth 1 -name a\ \* | xargs rm
rm: cannot remove ‘./a’: No such file or directory
rm: cannot remove ‘b’: No such file or directory

This is because it splits it's input on white-space to extract the file names. We can use another separator character; from man find:

  -print0
          True; print the full file name on the standard output,  followed
          by  a  null  character  (instead  of  the newline character that
          -print uses).  This allows file names that contain  newlines  or
          other  types  of white space to be correctly interpreted by pro‐
          grams that process the find output.  This option corresponds  to
          the -0 option of xargs.

So:

 find . -type f -name .\* -print0 | xargs -0 rm


来源:https://stackoverflow.com/questions/33488712/delete-nested-hidden-files-with-egrep-and-xargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!