As we seen in our previous articles we can use grep command in combination with two other commands to delete multiple files which has certain string in the file name or same extension in linux. The whole command looks like this:

Grep and delete files which has similar file name
ls | grep 'db_backup_*' | xargs rm -f

In the above command,

ls - lists the files in the current directory

grep - filters the output of "ls" command to list only files which has "db_backup_" in the file name

xargs - this command used to pass output of grep command to input another command, in our case it is "rm", which deletes the input files from the directory.

| - Pipe symbol used to combine two or more commands to run one by one.

If you want to grep and delete multiple files which has same extension, just slightly modify the grep condition in the above command, it will work. For example,
ls | grep '*.sql' | xargs rm -f

This command delete the files which has ".sql" extension.


Comments (0)
Leave a Comment

loader Posting your comment...