Linux find file that ends with

Recursively find files ending with specified pattern

I have a lot of folders with files ending with «-105×135.jpg», «-410×410.jpg» etc., «780-105×135.jpg» and «candyswing-2-klein-ohrringe-schale-038-135×160.jpg» for example which i need to find and delete, using online regex I’ve created this pattern: 9x..7.jpg , but find . -regex ‘8x..7.jpg’ didn`t show any results.

2 Answers 2

According to the man page, the -regex option is a match on the entire path, ie. the entire file name and also the entire directory-path portion, so you would need to precede your regex with .* . There are several explicit examples in the man page.

Also, keep in mind the option -regextype . The default (per the man page) is emacs , but other options are posix-awk , posix-basic , posix-egrep and posix-extended . Knock yourself out.

Thanks! It did work, but besides adding .* I needed to replace periods with 1 , for some reason periods didn’t work. I ended up with find -regex «.*[09]x768.jpg»

Great to hear. If you’re game to continue experimenting, try «.*[09]x6+.jpg» and «.*[09]x4<3>.jpg»

Another option would be to use bash’s globstar option:

The glob pattern above is slightly different that the regex you provided; the regex would allow any two characters after the x , not strictly numbers. In other words, a file named: somefile-135xyz9.jpg would match the regex, but not the above glob.

The glob recursively ( ** ) matches files that:

  • start with anything ( * )
  • have three numbers (three 8 )
  • followed by an x
  • followed by three numbers
  • followed by .jpg

One risk to this approach is if/when the number of matching files exceeds the command-line argument space. In that case, you could save the filenames in an array, then loop through the array individually.

files=(**/*973x494.jpg) for file in "$"; do echo Would: rm -- "$file"; done 
files=(**/*528x688.jpg) for file in "$"; do rm -- "$file"; done 

Источник

find directory or file that ends in any 3 characters

and this doesnt work,, what should I type to find any directory of files that ends with 3 or 4 or 5 or 6 or 7 . characters?

Are your three characters any characters, or three specific ones? If they are any characters, then the question is the same as «find names that are at least three characters long«. Right?

Do you mean that the rest of the file name may contain non-characters, while you want the end of the files to contain 3 to 7 characters? How do you define a non-character? Is that sequence of bytes forming valid characters in the current locale encoding? See also How to create string with invalid unicode characters, in Zsh? for other interpretations

3 Answers 3

find /etc -maxdepth 1 -regextype egrep -regex '.*/.$' 

This will find file or directory names in /etc/ that are exactly 3 characters long.

find /etc -maxdepth 1 -regextype egrep -regex '.*/.$' 

And this will find files or directories in /etc/ that are a minimum of 3 characters long.

find /etc -maxdepth 1 -regextype egrep -regex '.*/.$' 

And this will find files or directories in /etc that are anywhere from 3 to 7 characters long.

Читайте также:  Using awk in linux

The -maxdepth 1 prevents find from searching sub-directories of /etc.

If you want to restrict the match to directories only, add -type d after the -maxdepth 1 . For regular files, use -type f .

If you intend to do anything with the files/dirs found, you can use find’s -exec option. e.g.

find /etc -maxdepth 1 -regextype egrep -regex '.*/.$' -exec du -sch <> + 

or xargs (but use NUL separators to avoid problems with spaces, newlines, etc in filenames). This allows you to use any tool that can process NUL-separated input in the pipeline before xargs . e.g.:

find /etc -maxdepth 1 -regextype egrep -regex '.*/.$' -print0 | head -z -n 10 | xargs -0r ls -ld 

To list the names in a single directory (i.e. not recursively) that contain at least three characters, you may use any of the globbing patterns *. , . * or *. * . Each ? matches a single character, while * matches any number of characters.

To list such names under /etc with ls :

If you want to list the names that end in three specific characters (e.g. xyz ), then use *xyz as the pattern.

To search for such names recursively, you may (in bash ) use shopt -s globstar to enable the ** globbing pattern (matches recursively down into subdirectories) and then.

The ** pattern is enabled by default in the zsh shell.

To do something with these names (other than just calling ls ), use a loop:

shopt -s globstar for pathname in /etc/**/*. ; do # use "$pathname" to do something done 

In the dash shell or plain sh , the equivalent of this loop would be

find /etc -name '*. ' -exec sh -c ' for pathname do # use "$pathname" to do something done' sh <> + 

Your use of grep shows that you are confusing regular expressions with filename globbing patterns. In a regular expression, a dot ( . ) matches any one single character, while ? matches just the character ? (at least in basic regular expressions, which is what grep uses by default).

Filename patterns are also always anchored, so there’s no need to explicitly anchor the pattern with $ as in a regular expression (the pattern must match the complete filename though, so xyz matches exactly that name while *xyz matches any filename ending in xyz ).

Источник

Find Files in Linux Using the Command Line

Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.

When you have to find a file in Linux, it’s sometimes not as easy as finding a file in another operating system. This is especially true if you are running Linux without a graphical user interface and need to rely on the command line. This article covers the basics of how to find a file in Linux using the CLI. The find command in Linux is used to find a file (or files) by recursively filtering objects in the file system based on a simple conditional mechanism. You can use the find command to search for a file or directory on your file system. By using the -exec flag ( find -exec ), matches, which can be files, directories, symbolic links, system devices, etc., can be found and immediately processed within the same command.

Читайте также:  Share desktop with linux

Find a File in Linux by Name or Extension

Use find from the command line to locate a specific file by name or extension. The following example searches for *.err files in the /home/username/ directory and all sub-directories:

find /home/username/ -name "*.err" 

Using Common find Commands and Syntax to Find a File in Linux

find expressions take the following form:

find options starting/path expression 
  • The options attribute will control the find process’s behavior and optimization method.
  • The starting/path attribute will define the top-level directory where find begins filtering.
  • The expression attribute controls the tests that search the directory hierarchy to produce output.

Consider the following example command:

find -O3 -L /var/www/ -name "*.html" 

This command enables the maximum optimization level (-O3) and allows find to follow symbolic links ( -L ). find searches the entire directory tree beneath /var/www/ for files that end with .html .

Basic Examples

Command Description
find . -name testfile.txt Find a file called testfile.txt in current and sub-directories.
find /home -name *.jpg Find all .jpg files in the /home and sub-directories.
find . -type f -empty Find an empty file within the current directory.
find /home -user exampleuser -mtime -7 -iname «.db» Find all .db files (ignoring text case) modified in the last 7 days by a user named exampleuser.

Options and Optimization for find

The default configuration for find will ignore symbolic links (shortcut files). If you want find to follow and return symbolic links, you can add the -L option to the command, as shown in the example above.

find optimizes its filtering strategy to increase performance. Three user-selectable optimization levels are specified as -O1 , -O2 , and -O3 . The -O1 optimization is the default and forces find to filter based on filename before running all other tests.

Optimization at the -O2 level prioritizes file name filters, as in -O1 , and then runs all file-type filtering before proceeding with other more resource-intensive conditions. Level -O3 optimization allows find to perform the most severe optimization and reorders all tests based on their relative expense and the likelihood of their success.

Command Description
-O1 (Default) filter based on file name first.
-O2 File name first, then file type.
-O3 Allow find to automatically re-order the search based on efficient use of resources and likelihood of success.
-maxdepth X Search current directory as well as all sub-directories X levels deep.
-iname Search without regard for text case.
-not Return only results that do not match the test case.
-type f Search for files.
-type d Search for directories.
Читайте также:  Создать символическую ссылку linux

Find a File in Linux by Modification Time

The find command contains the ability to filter a directory hierarchy based on when the file was last modified:

find / -name "*conf" -mtime -7 find /home/exampleuser/ -name "*conf" -mtime -3 

The first command returns a list of all files in the entire file system that end with the characters conf and modified in the last seven days. The second command filters exampleuser user’s home directory for files with names that end with the characters conf and modified in the previous three days.

Use grep to Find a File in Linux Based on Content

The find command can only filter the directory hierarchy based on a file’s name and metadata. If you need to search based on the file’s content, use a tool like grep . Consider the following example:

find . -type f -exec grep "example" '<>' \; -print 

This searches every object in the current directory hierarchy ( . ) that is a file ( -type f ) and then runs the command grep «example» for every file that satisfies the conditions. The files that match are printed on the screen ( -print ). The curly braces ( <> ) are a placeholder for the find match results. The <> are enclosed in single quotes ( ‘ ) to avoid handing grep a malformed file name. The -exec command is terminated with a semicolon ( ; ), which should be escaped ( \; ) to avoid interpretation by the shell.

How to Find and Process a File in Linux

The -exec option runs commands against every object that matches the find expression. Consider the following example:

find . -name "rc.conf" -exec chmod o+r '<>' \; 

This filters every object in the current hierarchy ( . ) for files named rc.conf and runs the chmod o+r command to modify the find results’ file permissions.

The commands run with the -exec are executed in the find process’s root directory. Use -execdir to perform the specified command in the directory where the match resides. This may alleviate security concerns and produce a more desirable performance for some operations.

The -exec or -execdir options run without further prompts. If you prefer to be prompted before action is taken, replace -exec with -ok or -execdir with -okdir .

How to Find and Delete a File in Linux

To delete the files that end up matching your search, you can add -delete at the end of the expression. Do this only when you are positive the results will only match the files you wish to delete.

In the following example, find locates all files in the hierarchy starting at the current directory and fully recursing into the directory tree. In this example, find will delete all files that end with the characters .err :

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

This page was originally published on Monday, October 25, 2010.

Источник

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