To delete all files in a directory in Linux, except for a few files that you want to keep, you can use the rm
command with the !
operator and the -I
option.
For example, to delete all files in the current directory except for the files file1.txt
and file2.txt
, you can use the following command:
rm !(file1.txt|file2.txt)Source:www.lautturi.com
This will delete all files in the current directory, except for file1.txt
and file2.txt
.
You can also use the find
command to delete all files in a directory, except for a few files that you want to keep. For example, to delete all files in the /tmp
directory except for the files file1.txt
and file2.txt
, you can use the following command:
find /tmp -type f ! -name "file1.txt" ! -name "file2.txt" -delete
This will find all files in the /tmp
directory, except for file1.txt
and file2.txt
, and delete them.
It is important to use caution when deleting files, as it is not possible to recover deleted files. Make sure that you have a backup of any important data before deleting any files.