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

后端 未结 11 1108
野趣味
野趣味 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 16:05

    You can type it right in the command-line or use this keystroke in the script

    files=`ls -l | grep -v "my_favorite_dir"`; for file in $files; do rm -rvf $file; done
    

    P.S. I suggest -i switch for rm to prevent delition of important data.

    P.P.S You can write the small script based on this solution and place it to the /usr/bin (e.g. /usr/bin/rmf). Now you can use it as and ordinary app:

    rmf my_favorite_dir
    

    The script looks like (just a sketch):

    #!/bin/sh
    
    if [[ -z $1 ]]; then
        files=`ls -l`
    else
        files=`ls -l | grep -v $1`
    fi;
    
    for file in $files; do
        rm -rvi $file
    done;
    

提交回复
热议问题