- Как использовать regex с командой find?
- 7 ответов
- Using Grep & Regular Expressions to Search for Text Patterns in Linux
- Introduction
- Prerequisites
- Basic Usage
- Common Options
- Regular Expressions
- Literal Matches
- Anchor Matches
- Matching Any Character
- Bracket Expressions
- Repeat Pattern Zero or More Times
- Escaping Meta-Characters
- Extended Regular Expressions
- Grouping
- Alternation
- Quantifiers
- Specifying Match Repetition
- Conclusion
Как использовать regex с командой find?
У меня есть некоторые изображения с именем сгенерированной строки uuid1. Например 81397018-b84a-11e0-9d2a-001b77dc0bed.формат jpg. Я хочу узнать все эти изображения, используя команду «найти»:
но это не работает. Что-то не так с регулярным выражением? Кто-нибудь может мне помочь?
7 ответов
обратите внимание, что нужно указать .*/ в начале find соответствует всему пути.
моя версия find:
на -regex найти выражение соответствует все имя, включая относительный путь от текущего каталога. Для find . этого всегда начинается с ./ , то любые каталоги.
и emacs регулярные выражения, которые имеют другие правила экранирования, чем обычные регулярные выражения egrep.
если все они находятся непосредственно в текущем каталоге, то
должны работать. (Я не совсем уверен, — я не могу получить подсчитано повторение, чтобы работать здесь.) Можно выбрать для egrep выражения -regextype posix-egrep :
(обратите внимание, что все сказанное здесь для GNU find, я ничего не знаю о BSD, который также является значением по умолчанию для Mac.)
судя по другим ответам, кажется, это может быть ошибка find.
однако вы можете сделать это таким образом:
find . * | grep -P «[a-f0-9\-]<36>\.jpg»
возможно, вам придется немного настроить grep и использовать разные параметры в зависимости от того, что вы хотите, но это работает.
попробуйте использовать одинарные кавычки ( ‘ ), чтобы избежать экранирования оболочки вашей строки. Помните, что выражение должно соответствовать всему пути, т. е. должно выглядеть так:
кроме того, кажется, что моя находка (GNU 4.4.2) знает только основные регулярные выражения, особенно синтаксис <36>. Думаю, тебе придется обойтись без этого.
вы должны использовать абсолютный путь к каталогу при применении инструкции с регулярным выражением. В вашем примере
следует изменить на
в большинстве систем Linux некоторые дисциплины в регулярном выражении не могут быть распознаны этой системой, поэтому вы должны явно указать-regexty как
простой способ — вы можете указать .* в начале, потому что найти весь путь.
на Mac (BSD найти): то же, что и принятый ответ, .*/ префикс необходим для соответствия полному пути:
man find говорит -E использует расширенную поддержку регулярных выражений
Источник
Using Grep & Regular Expressions to Search for Text Patterns in Linux
Last Validated on September 25, 2021 Originally Published on July 22, 2013
Introduction
The grep command is one of the most useful commands in a Linux terminal environment. The name grep stands for “global regular expression print”. This means that you can use grep to check whether the input it receives matches a specified pattern. This seemingly trivial program is extremely powerful; its ability to sort input based on complex rules makes it a popular link in many command chains.
In this tutorial, you will explore the grep command’s options, and then you’ll dive into using regular expressions to do more advanced searching.
Prerequisites
To follow along with this guide, you will need access to a computer running a Linux-based operating system. This can either be a virtual private server which you’ve connected to with SSH or your local machine. Note that this tutorial was validated using a Linux server running Ubuntu 20.04, but the examples given should work on a computer running any version of any Linux distribution.
If you plan to use a remote server to follow this guide, we encourage you to first complete our Initial Server Setup guide. Doing so will set you up with a secure server environment — including a non-root user with sudo privileges and a firewall configured with UFW — which you can use to build your Linux skills.
As an alternative, we encourage you to use an interactive terminal embedded on this page to experiment with the sample commands in this tutorial. Click the following Launch an Interactive Terminal! button to open a terminal window and begin working with a Linux (Ubuntu) environment.
Basic Usage
In this tutorial, you’ll use grep to search the GNU General Public License version 3 for various words and phrases.
If you’re on an Ubuntu system, you can find the file in the /usr/share/common-licenses folder. Copy it to your home directory:
If you’re on another system, use the curl command to download a copy:
You’ll also use the BSD license file in this tutorial. On Linux, you can copy that to your home directory with the following command:
If you’re on another system, create the file with the following command:
Now that you have the files, you can start working with grep .
In the most basic form, you use grep to match literal patterns within a text file. This means that if you pass grep a word to search for, it will print out every line in the file containing that word.
Execute the following command to use grep to search for every line that contains the word GNU :
The first argument, GNU , is the pattern you’re searching for, while the second argument, GPL-3 , is the input file you wish to search.
The resulting output will be every line containing the pattern text:
On some systems, the pattern you searched for will be highlighted in the output.
Common Options
By default, grep will search for the exact specified pattern within the input file and return the lines it finds. You can make this behavior more useful though by adding some optional flags to grep .
If you want grep to ignore the “case” of your search parameter and search for both upper- and lower-case variations, you can specify the -i or —ignore-case option.
Search for each instance of the word license (with upper, lower, or mixed cases) in the same file as before with the following command:
The results contain: LICENSE , license , and License :
If there was an instance with LiCeNsE , that would have been returned as well.
If you want to find all lines that do not contain a specified pattern, you can use the -v or —invert-match option.
Search for every line that does not contain the word the in the BSD license with the following command:
You’ll receive this output:
Since you did not specify the “ignore case” option, the last two items were returned as not having the word the .
It is often useful to know the line number that the matches occur on. You can do this by using the -n or —line-number option. Re-run the previous example with this flag added:
This will return the following text:
Now you can reference the line number if you want to make changes to every line that does not contain the . This is especially handy when working with source code.
Regular Expressions
In the introduction, you learned that grep stands for “global regular expression print”. A “regular expression” is a text string that describes a particular search pattern.
Different applications and programming languages implement regular expressions slightly differently. In this tutorial you will only be exploring a small subset of the way that grep describes its patterns.
Literal Matches
In the previous examples in this tutorial, when you searched for the words GNU and the , you were actually searching for basic regular expressions which matched the exact string of characters GNU and the . Patterns that exactly specify the characters to be matched are called “literals” because they match the pattern literally, character-for-character.
It is helpful to think of these as matching a string of characters rather than matching a word. This will become a more important distinction as you learn more complex patterns.
All alphabetical and numerical characters (as well as certain other characters) are matched literally unless modified by other expression mechanisms.
Anchor Matches
Anchors are special characters that specify where in the line a match must occur to be valid.
For instance, using anchors, you can specify that you only want to know about the lines that match GNU at the very beginning of the line. To do this, you could use the ^ anchor before the literal string.
Run the following command to search the GPL-3 file and find lines where GNU occurs at the very beginning of a line:
This command will return the following two lines:
Similarly, you use the $ anchor at the end of a pattern to indicate that the match will only be valid if it occurs at the very end of a line.
This command will match every line ending with the word and in the GPL-3 file:
You’ll receive this output:
Matching Any Character
The period character (.) is used in regular expressions to mean that any single character can exist at the specified location.
For example, to match anything in the GPL-3 file that has two characters and then the string cept , you would use the following pattern:
This command returns the following output:
This output has instances of both accept and except and variations of the two words. The pattern would also have matched z2cept if that was found as well.
Bracket Expressions
By placing a group of characters within brackets ( \[ and \] ), you can specify that the character at that position can be any one character found within the bracket group.
For example, to find the lines that contain too or two , you would specify those variations succinctly by using the following pattern:
The output shows that both variations exist in the file:
Bracket notation gives you some interesting options. You can have the pattern match anything except the characters within a bracket by beginning the list of characters within the brackets with a ^ character.
This example is like the pattern .ode , but will not match the pattern code :
Here’s the output you’ll receive:
Notice that in the second line returned, there is, in fact, the word code . This is not a failure of the regular expression or grep. Rather, this line was returned because earlier in the line, the pattern mode , found within the word model , was found. The line was returned because there was an instance that matched the pattern.
Another helpful feature of brackets is that you can specify a range of characters instead of individually typing every available character.
This means that if you want to find every line that begins with a capital letter, you can use the following pattern:
Here’s the output this expression returns:
Due to some legacy sorting issues, it is often more accurate to use POSIX character classes instead of character ranges like you just used.
To discuss every POSIX character class would be beyond the scope of this guide, but an example that would accomplish the same procedure as the previous example uses the \[:upper:\] character class within a bracket selector:
The output will be the same as before.
Repeat Pattern Zero or More Times
Finally, one of the most commonly used meta-characters is the asterisk, or * , which means “repeat the previous character or expression zero or more times”.
To find each line in the GPL-3 file that contains an opening and closing parenthesis, with only letters and single spaces in between, use the following expression:
You’ll get the following output:
So far you’ve used periods, asterisks, and other characters in your expressions, but sometimes you need to search for those characters specifically.
Escaping Meta-Characters
There are times where you’ll need to search for a literal period or a literal opening bracket, especially when working with source code or configuration files. Because these characters have special meaning in regular expressions, you need to “escape” these characters to tell grep that you do not wish to use their special meaning in this case.
You escape characters by using the backslash character ( \ ) in front of the character that would normally have a special meaning.
For instance, to find any line that begins with a capital letter and ends with a period, use the following expression which escapes the ending period so that it represents a literal period instead of the usual “any character” meaning:
This is the output you’ll see:
Now let’s look at other regular expression options.
Extended Regular Expressions
The grep command supports a more extensive regular expression language by using the -E flag or by calling the egrep command instead of grep .
These options open up the capabilities of “extended regular expressions”. Extended regular expressions include all of the basic meta-characters, along with additional meta-characters to express more complex matches.
Grouping
One of the most useful abilities that extended regular expressions open up is the ability to group expressions together to manipulate or reference as one unit.
To group expressions together, wrap them in parentheses. If you would like to use parentheses without using extended regular expressions, you can escape them with the backslash to enable this functionality. This means that the following three expressions are functionally equivalent:
Alternation
Similar to how bracket expressions can specify different possible choices for single character matches, alternation allows you to specify alternative matches for strings or expression sets.
To indicate alternation, use the pipe character | . These are often used within parenthetical grouping to specify that one of two or more possibilities should be considered a match.
The following will find either GPL or General Public License in the text:
The output looks like this:
Alternation can select between more than two choices by adding additional choices within the selection group separated by additional pipe ( | ) characters.
Quantifiers
Like the * meta-character that matched the previous character or character set zero or more times, there are other meta-characters available in extended regular expressions that specify the number of occurrences.
To match a character zero or one times, you can use the ? character. This makes character or character sets that came before optional, in essence.
The following matches copyright and right by putting copy in an optional group:
You’ll receive this output:
The + character matches an expression one or more times. This is almost like the * meta-character, but with the + character, the expression must match at least once.
The following expression matches the string free plus one or more characters that are not white space characters:
You’ll see this output:
Specifying Match Repetition
To specify the number of times that a match is repeated, use the brace characters ( < and >). These characters let you specify an exact number, a range, or an upper or lower bounds to the amount of times an expression can match.
Use the following expression to find all of the lines in the GPL-3 file that contain triple-vowels:
Each line returned has a word with three vowels:
To match any words that have between 16 and 20 characters, use the following expression:
Here’s this command’s output:
Only lines containing words within that length are displayed.
Conclusion
grep is useful in finding patterns within files or within the file system hierarchy, so it’s worth spending time getting comfortable with its options and syntax.
Regular expressions are even more versatile, and can be used with many popular programs. For instance, many text editors implement regular expressions for searching and replacing text.
Furthermore, most modern programming languages use regular expressions to perform procedures on specific pieces of data. Once you understand regular expressions, you’ll be able to transfer that knowledge to many common computer-related tasks, from performing advanced searches in your text editor to validating user input.
Источник