Linux find file and remove

6 find exec rm Command Examples to Delete Files

Linux find command is a powerful tool that can be used to locate and manage files and directories based on a wide range of search criteria.

This post will cover how to delete files with find exec rm in Linux. However, some solutions in this article can be dangerous if we don’t correctly use them. We need to test this before we run it in the production environment.

What is find exec rm?

The find, exec, and rm commands are frequently used together in Linux to search for files or directories that match certain criteria and then delete them.

This command combines three commands together to remove any found directories or files from your system. Find exec rm is very helpful for quickly deleting files or directories based on their permissions, type, date, ownership, size, and more.

Find command Syntax in Linux

The find command in Linux is used to search for files and directories in a specified location. Its syntax is as follows:

Here is a brief explanation of each element of the command:

  • [path]: This is the starting point for the search. You can specify a directory to start the search from. If you don’t specify a path, the search starts from the current directory.
  • [expression]: This is a logical expression that determines which files to include in the search results. The expression can include various operators such as -and, -or, and -not, as well as various tests such as -name, -type, and -size. You can also use parentheses to group expressions and make complex searches.

For example, to search for all files in the current directory and its subdirectories that have the extension .txt, you can use the following command:

This command starts the search from the current directory (.), searches for files with the extension .txt (-name “*.txt”), and returns a list of all matching files and their paths.

For example, the result of this command might look something like:

./file1.txt
./dir1/file2.txt
./dir2/subdir/file3.txt

This means that there are three files that match the search criteria, named “file1.txt”, “file2.txt”, and “file3.txt”, and they are located in the current directory and its subdirectories. The . at the beginning of the command specifies that the search should start from the current directory.

Some common expression include -name to search for files by name, -type to search for files by type, -mtime to search for files by modification time, and -size to search for files by size. You can combine multiple options to refine your search criteria.

Find exec rm command Syntax

The syntax of the command is as follows:

find [path] [expression] -exec rm <> \;

Here is a brief explanation of each element of the command:

  • -exec: This option allows you to execute a command on each matching file. In this case, the command is rm to delete the file.
  • <> \;: This is a placeholder for the name of the matching file, and the \; indicates the end of the -exec option.
Читайте также:  Аналог скетчап для линукс

For example, to search for all files in the current directory and its subdirectories that have the extension .txt and delete them, you can use the following command:

This command starts the search from the current directory (.), searches for files with the extension .txt (-name “*.txt”), and deletes each matching file (-exec rm <> \;).

Be careful when using the rm command, as it permanently deletes files and there is no undo option.

Therefore, it’s always a good idea to double-check the search results before executing the rm command.

Delete Files with a specific name

The -name option in the find command is used to search for files or directories based on their names. It allows you to specify a pattern or exact name to match when searching for files.

Here’s how the -name option works:

  • -name pattern: This option selects files or directories whose names match the specified pattern.
  • pattern can be a complete filename or include wildcard characters for partial matching. Common wildcard characters are * (matches any sequence of characters) and ? (matches any single character).
  • The pattern is case-sensitive unless you use the -iname option instead, which performs a case-insensitive match.

Here are a few examples to illustrate the usage:

  • -name myfile.txt: Select files or directories with the exact name “myfile.txt”.
  • -name “*.txt”: Select files or directories with names ending in “.txt”.
  • -name “file*”: Select files or directories with names starting with “file”.
  • -iname “NAME*”: Select files or directories with names starting with “name” or “NAME” (case-insensitive).

You can combine the -name option with other find options, such as specifying the starting directory, specifying the type of files to search (-type f for regular files), and using the -exec option to perform actions on the matched files or directories.

Every time the find command identifies a file with the .c suffix, the rm command deletes that file.

find /directory -name “*.c” -exec rm <> \;

Delete files in multiple directories

If we want to search and delete all files with a given name in multiple directories,
we can either start the search at root folder, or if we know the directories, we can specify them.

find /path1 /path2 -name failed*.* -type f -exec rm <> \;

Delete Files Older Than x Days on Linux

find /path/to/files* -type f -mtime +5 -exec rm <> \;

Replace /path/to/files with the actual directory path where your files are located. The -type f option ensures that only regular files (not directories or other types) are considered.

The -mtime +x option specifies that files modified more than x days ago should be selected, where x is the number of days. The -exec rm <> \; part executes the rm command on each selected file, removing them.

Delete Files with modifying time

The -mmin option in the find command is used to specify the time criteria based on the file’s modification time. It allows you to search for files based on the number of minutes since the file was last modified.

Читайте также:  Arch linux grub install efi

Here’s a breakdown of how the -mmin option works:

  • -mmin n: This option selects files based on the time since the file’s content was last modified.
  • n represents the number of minutes. You can use positive integers, negative integers, or zero.
    • Positive integers: Files modified n minutes ago or more in the past will be selected.
    • Negative integers: Files modified within the last n minutes will be selected.
    • Zero: Only files modified within the last minute will be selected.

    Here are a few examples to illustrate the usage:

    • -mmin +60: Select files modified more than 60 minutes ago.
    • -mmin -60: Select files modified within the last 60 minutes.
    • -mmin 0: Select files modified within the last minute.

    By combining the -mmin option with other find options, such as -type f to select only regular files, and using the -exec option to perform an action (e.g., rm to remove the files), you can create powerful file management commands based on time criteria.

    To remove the files that are modified within 60 minutes, type:

    find /path -mmin -60 -exec rm <> \;

    The -mmin -60 option specifies that files modified within the last 60 minutes should be selected.

    Delete Large files

    The -size option in the find command is used to search for files based on their sizes. It allows you to specify the file size as a criterion when searching for files.

    Here’s how the -size option works:

    • -size n[cwbkMG]: This option selects files that match the specified size criterion.
    • n represents the size value, and you can specify it as a positive integer.
    • The optional size indicator can be used to specify the unit of the size:
      • c for bytes
      • w for two-byte words
      • b for 512-byte blocks
      • k for kilobytes (default if no size indicator is provided)
      • M for megabytes
      • G for gigabytes

      Here are a few examples to illustrate the usage:

      • -size +100k: Select files that are larger than 100 kilobytes.
      • -size -1M: Select files that are smaller than 1 megabyte.
      • -size 10M: Select files that are exactly 10 megabytes in size.
      • -size +1G: Select files that are larger than 1 gigabyte.

      You can combine the -size option with other find options, such as specifying the starting directory, specifying the type of files to search (-type f for regular files), and using the -exec option to perform actions on the matched files.

      The first step is to find files larger than 200 MB.

      The next target is to remove these files. This can be done by:

      find /path -type f -size +200M -exec rm <> \;

      Advanced find exec rm examples

      To remove all files named a.out or *.o that are not accessed for a week and that are not mounted by using nfs, type:

      find / \( -name a.out -o -name ‘*.o’ \) -atime +7 ! -fstype nfs -exec rm <> \;

      • find: The command itself, used to search for files and perform actions on them.
      • /: The starting directory for the search. In this case, it is the root directory (/), which means the search will cover the entire file system.
      • \( -name a.out -o -name ‘*.o’ \): This is a logical expression that searches for files matching specific names. It consists of two parts:
        • -name a.out: Matches files with the exact name “a.out”.
        • -o: Logical operator “OR”.
        • -name ‘*.o’: Matches files with names ending in “.o”.

        Note: The number that is used within the -atime expression is +7. It is the correct entry if we want the command to act on files that are not accessed for more than a week (seven 24-hour periods).

        David is a Cloud & DevOps Enthusiast. He has years of experience as a Linux engineer. He had working experience in AMD, EMC. He likes Linux, Python, bash, and more. He is a technical blogger and a Software Engineer. He enjoys sharing his learning and contributing to open-source.

        howtouselinux.com is dedicated to providing comprehensive information on using Linux.

        We hope you find our site helpful and informative.

        Источник

        Delete a list of files with find and grep

        I want to delete all files which have names containing a specific word, e.g. «car». So far, I came up with this:

        12 Answers 12

        or pass the output of your pipeline to xargs :

        find | grep car | xargs rm -f 

        Note that these are very blunt tools, and you are likely to remove files that you did not intend to remove. Also, no effort is made here to deal with files that contain characters such as whitespace (including newlines) or leading dashes. Be warned.

        +1. But on the first few runs: change «rm» to «echo rm» . and verify that it only outputs file you really want to delete, and no others ^^

        @nhahtdh: xargs: illegal option — d ; all the world is not LInux. And what about directories that contain \n in their name? If you worry about whitespace, you should use find —print0 . xargs -0

        Please be aware that this will not work if your files contain unusual characters (like spaces) or start with a dash. Please see my answer for a fix.

        To view what you are going to delete first, since rm -fr is such a dangerous command:

        find /path/to/file/ | grep car | xargs ls -lh 

        Then if the results are what you want, run the real command by removing the ls -lh , replacing it with rm -fr

        find /path/to/file/ | grep car | xargs rm -fr 

        It does exactly what you ask, logically running rm -rf on the what grep car returns from the output of find . which is a list of every file and folder recursively.

        You really want to use find with -print0 and rm with — :

        find [dir] [options] -print0 | grep --null-data [pattern] | xargs -0 rm -- 

        A concrete example (removing all files below the current directory containing car in their filename):

        find . -print0 | grep --null-data car | xargs -0 rm -- 
        • -print0 , —null-data and -0 change the handling of the input/output from parsed as tokens separated by whitespace to parsed as tokens separated by the \0 -character. This allows the handling of unusual filenames (see man find for details)
        • rm — makes sure to actually remove files starting with a — instead of treating them as parameters to rm . In case there is a file called -rf and do find . -print0 | grep —null-data r | xargs -0 rm , the file -rf will possibly not be removed, but alter the behaviour of rm on the other files.

        Источник

Оцените статью
Adblock
detector