Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use "rm" command with inverse match

Tags:

bash

I want to remove all files that do not match R1.fastq.gz in my list of files. How do I use rm with inverse match?

like image 867
user2300940 Avatar asked Apr 29 '18 13:04

user2300940


People also ask

What does the command rm /* * do?

The rm command is used to delete files.

Does rm * remove all files?

The rm command removes the entries for a specified file, group of files, or certain select files from a list within a directory. User confirmation, read permission, and write permission are not required before a file is removed when you use the rm command.

What is the difference between the command rm R and rm R?

The two options are equivalent, by default, rm does not remove directories. And by using the --recursive (-r or -R) option to remove each listed directory, too, along with all of its contents.

What will happen if you run rm * * in a folder and in the root directory?

All non-hidden files and directories in your home directory will be deleted. Any contents of any userfs -mounted partitions (networked or otherwise) will be deleted.


1 Answers

Use the extended pattern syntax available in bash:

shopt -s extglob
printf '%s\n' !(R1.fastq.gz)  # To verify the list of files the pattern matches
rm !(R1.fastq.gz)  # To actually remove them.

Or, use find:

find . ! -name R1.fastq.gz -print         # Verify
find . ! -name R1.fastq.gz -exec rm {} +  # Delete

If your version of find supports it, you can use -delete instead of -exec rm {} +:

find . ! -name R1.fastq.gz -delete
like image 142
chepner Avatar answered Oct 21 '22 03:10

chepner