Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regex in file find

Tags:

bash

unix

I was trying to find all files dated and all files 3 days or more ago.

find /home/test -name 'test.log.\d{4}-d{2}-d{2}.zip' -mtime 3 

It is not listing anything. What is wrong with it?

like image 603
Tree Avatar asked Mar 09 '11 17:03

Tree


People also ask

Can I use regex with find?

To use regular expressions, open either the Find pane or the Replace pane and select the Use check box. When you next click Find Next, the search string is evaluated as a regular expression. When a regular expression contains characters, it usually means that the text being searched must match those characters.

How does regex search work?

A regex engine executes the regex one character at a time in left-to-right order. This input string itself is parsed one character at a time, in left-to-right order. Once a character is matched, it's said to be consumed from the input, and the engine moves to the next input character.

What is a regex file?

A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids. You are probably familiar with wildcard notations such as *. txt to find all text files in a file manager.

Can you use regex in Linux command line?

Regular expressions are special characters or sets of characters that help us to search for data and match the complex pattern. Regexps are most commonly used with the Linux commands:- grep, sed, tr, vi.


2 Answers

find /home/test -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip' -mtime +3 
  1. -name uses globular expressions, aka wildcards. What you want is -regex
  2. To use intervals as you intend, you need to tell find to use Extended Regular Expressions via the -regextype posix-extended flag
  3. You need to escape out the periods because in regex a period has the special meaning of any single character. What you want is a literal period denoted by \.
  4. To match only those files that are greater than 3 days old, you need to prefix your number with a + as in -mtime +3.

Proof of Concept

$ find . -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip' ./test.log.1234-12-12.zip 
like image 108
SiegeX Avatar answered Oct 21 '22 00:10

SiegeX


Use -regex not -name, and be aware that the regex matches against what find would print, e.g. "/home/test/test.log" not "test.log"

like image 44
Erik Avatar answered Oct 21 '22 01:10

Erik