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

后端 未结 11 1056
野趣味
野趣味 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:59
    mv subdir/preciousfile  ./
    rm -rf subdir
    mkdir subdir
    mv preciousfile subdir/
    

    This looks tedious, but it is rather safe

    • avoids complex logic
    • never use rm -rf *, its results depend on your current directory (which could be / ;-)
    • never use a globbing *: its expansion is limited by ARGV_MAX.
    • allows you to check the error after each command, and maybe avoid the disaster caused by the next command.
    • avoids nasty problems caused by space or NL in the filenames.
    0 讨论(0)
  • 2021-02-02 16:02

    At least in zsh

    rm -rf ^filename
    

    could be an option, if you only want to preserve one single file.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2021-02-02 16:06

    you need to use regular expression for this. Write a regular expression which selects all other files except the one you need.

    0 讨论(0)
  • 2021-02-02 16:10

    I see a lot of longwinded means here, that work, but with a/ b/ c/ d/ e/

     rm -rf *.* !(b*) 
    

    this removes everything except directory b/ and its contents (assuming your file is in b/. Then just cd b/ and

    rm -rf *.* !(filename) 
    

    to remove everything else, but the file (named "filename") that you want to keep.

    0 讨论(0)
提交回复
热议问题