In Linux, the RM + grep command deletes all files except the specified file. Previous/next article 10:17:38/personal classification: liunx (185)/comment (0)/score (0/0) this afternoon, I was asked how to delete all the files in a directory except the desired files. I thought about whether grep and RM work properly. After reading the information, we came up with a command: the process is as follows. First, in a directory: Zhou @ ZHOU :~ /Linuxc/file/test $ LS1 23 sdfwe 88888888 AABB Ag ghdda
Mmm2 3 aaaaaaaa ABC asdg llllllll wwwwwzhou @ ZHOU :~ /Linuxc/file/test $ then I want to delete all the files except the string AA, that is, the files AABB and aaaaaaaa, to delete all others, run the following command: Zhou @ ZHOU :~ /Linuxc/file/test $ RM 'ls | grep-V "AA" 'and check Zhou @ ZHOU :~ /Linuxc/file/test $ lsaaaaaaaa aabbzhou @ ZHOU :~ /Linuxc/file/test $. Let's briefly explain the command: Rm
Delete the file 'ls | grep-V "AA" 'specified later. Remember to enclose it in reverse quotation marks (the quotation marks are placed on the left of the number 1 on the standard keyboard). ls: view all the files in the current directory, and use the grep command to filter grep-V "AA" to find the strings without "AA. Next, list the files whose names do not contain the "AA" string and delete them. OK. In fact, it was easy to say. At that time, I also made a long time, because I didn't have much access to grep before, so at first I came up with a way to use regular expressions, but in the process of doing it, we suddenly found grep to make a good thing, so we used it. The preceding command deletes a file with a "AA" string. What if I only want to leave the file AA? Simple Zhou @ ZHOU :~ /Linuxc/file/test $
Rm 'ls | grep-V "^ AA $" 'is followed by a ^ symbol before AA, followed by a $ symbol indicating the end character. This is a perfect match. Okay, that's all. I hope this useful command will be used in the future.