Using find - Deleting all files/directories (in Linux ) except any one

后端 未结 11 1280
野趣味
野趣味 2021-02-02 15:12

If we want to delete all files and directories we use, rm -rf *.

But what if i want all files and directories be deleted at a shot, except one particular fi

11条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-02 15:47

    find can be a very good friend:

    $ ls
    a/  b/  c/
    $ find * -maxdepth 0 -name 'b' -prune -o -exec rm -rf '{}' ';'
    $ ls
    b/
    $ 
    

    Explanation:

    • find * -maxdepth 0: select everything selected by * without descending into any directories

    • -name 'b' -prune: do not bother (-prune) with anything that matches the condition -name 'b'

    • -o -exec rm -rf '{}' ';': call rm -rf for everything else

    By the way, another, possibly simpler, way would be to move or rename your favourite directory so that it is not in the way:

    $ ls
    a/  b/  c/
    $ mv b .b
    $ ls
    a/  c/
    $ rm -rf *
    $ mv .b b
    $ ls
    b/
    

提交回复
热议问题