

This will print the names of all files where "pattern2" appears after "pattern1", or where both appear on the same line: $ echo "abc Tail $f -n +$(grep -n "pattern1" $f | head -n1 | cut -d : -f 1) 2>/dev/null \ Formatted more readably: for f in FILEGLOB do This is highly experimental and grep -P may warn ofĪs an alternative to Balu Mohan's answer, it is possible to enforce the order of the patterns using only grep, head and tail: for f in FILEGLOB do tail $f -n +$(grep -n "pattern1" $f | head -n1 | cut -d : -f 1) 2>/dev/null | grep "pattern2" &>/dev/null & echo $f done Interpret PATTERN as a Perl regular expression (PCRE, seeīelow). To determine if your version is new enough, run man grep and see if something similar to this appears near the top: -P, -perl-regexp anything: grep -Pzo "abc(.|\n)*efg" /tmp/tes*īlah grep -Pzl "abc(.|\n)*efg" /tmp/tes* Note that the 'z' is necessary for multiline and the '(.|\n)' means to match either 'anything other than newline' or 'newline' - i.e. Here is the output showing that the first shows the matched string and the second shows only the filename (typical -o is to show match and typical -l is to show only filename). I copied the text as /tmp/test1 and deleted the 'g' and saved as /tmp/test2. This only works because the pattern is suitable: 'alpha portion' is specific enough to pull out what you want. In the example of the OP's question, I think the following options work nicely, with the second best matching how I understand the question: grep -Pzo "abc(.|\n)*efg" /tmp/tes* The first grep would remove any lines that didn't match your overall patern, the second grep (which has -only-matching specified) would display the alpha portion of the name. With practice, you can use regex effectively, as you can use it with other Linux commands as well.
#Using grep regex install#
When you use grep, it uses BRE as default.I relied heavily on pcregrep, but with newer grep you do not need to install pcregrep for many of its features. Regex, by definition, is an advanced output-filtering pattern.Pearl Compatible Regular Expressions (PCRE).grep -options Īlso, you’ll need to know about three regex syntax options. Basic understanding of grep command usage.
:max_bytes(150000):strip_icc()/grep-ea33e54fc7ed425283d6bec7baa458b6.jpg)

That’s because regex is an advanced output-filtering tool that lets you input a sequence of characters for matching. However, grep with regex (regular expression) can change how you approach pattern searching and matching. You can use it to match patterns and print output to the terminal. As a Linux user, you can use grep to search files and directories.
