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

后端 未结 11 1054
野趣味
野趣味 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:54

    Short answer

    ls | grep -v "z.txt" | xargs rm
    

    Details:

    The thought process for the above command is :

    • List all files (ls)
    • Ignore one file named "z.txt" (grep -v "z.txt")
    • Delete the listed files other than z.txt (xargs rm)

    Example

    Create 5 files as shown below:

    echo "a.txt b.txt c.txt d.txt z.txt" | xargs touch
    

    List all files except z.txt

    ls|grep -v "z.txt"
    
    a.txt
    b.txt
    c.txt
    d.txt
    

    We can now delete(rm) the listed files by using the xargs utility :

    ls|grep -v "z.txt"|xargs rm
    

提交回复
热议问题