Home > Mobile >  How to delete all files in a dir except ones with a certain pattern in their name?
How to delete all files in a dir except ones with a certain pattern in their name?

Time:07-08

I have a lot of kernel .deb files from my custom kerenls. I would like to write a bash that would delete all the old files except the ones associated with the currently installed kernel version. My script:

#!/bin/bash
version='uname -r'
$version
dir=~/Installed-kernels
ls | grep -v '$version*' | xargs rm

Unfortunately, this deletes all files in the dir. How can I get the currently installed kernel version and set said version as a perimeter with? Each .deb I want to keep contains the kernel version (5.18.8) but have other strings in their name (linux-headers-5.18.8_5.18.8_amd64.deb).

Edit: I am only deleting .deb files inside the noted directory. The current list of file names in the tree are

 linux-headers-5.18.8-lz-xan1_5.18.8-lz-1_amd64.deb
 linux-libc-dev_5.18.8-lz-1_amd64.deb
 linux-image-5.18.8-lz-xan1_5.18.8-lz-1_amd64.deb

CodePudding user response:

This can be done as a one-liner, though I've preserved your variables:

#!/bin/bash
version="$(uname -r)"
dir="$HOME/Installed-kernels"

find "$dir" -maxdepth 1 -type f -not -name "*$version*" -print0 |xargs -0 rm

To set a variable to the output of a command, you need either $(…) or `…`, ideally wrapped in double-quotes to preserve spacing. A tilde isn't always interpreted correctly when passed through variables, so I expanded that out to $HOME.

The find command is much safer to parse than the output of ls, plus it lets you better filter things. In this case, -maxdepth 1 will look at just that directory (no recursion), -type f seeks only files, and -not -name "*$version*" removes paths or filenames that match the kernel version (which is a glob, not a regex—you'd otherwise have to escape the dots). Also note those quotes; we want find to see the asterisks, and without the quotes, the shell will expand the glob prematurely. The -print0 and corresponding -0 ensure that you preserve spacing by delimiting entries with null characters.

You can remove the prompts regarding read-only files with rm -f.

If you also want to delete directories, remove the -type f part and add -r to the end of that final line.

  • Related