In Linux, the RM + grep command deletes all files except the specified file.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.