Find pattern in file

[problem]

You need to find a pattern in a file. Using regular expression.

[/problem]

[solution]

Normal command to display something in a file, is grep.


grep "pattern" filename

[/solution]

[example]

You can also display the line number it occured on (-n) and ignore case (-i):


grep -n -i "pattern" filename

Also you can match more than one pattern:


egrep "patternA|patternB" filename

To match the beginning of a line (^) or the end of line ($) – this will only match lines with this specific pattern on:


grep "^patternA$" filename

We can also use wildcards and ranges – this will match any line with PATTERN in it followed by any amount of numbers:


grep "^.*PATTERN[0-9]*$" filename

[/example]

[reference]

[tags]grep, regular expression, Unix Coding School[/tags]

[/reference]

If you have found my website useful, please consider buying me a coffee below 😉

Leave a Reply

Your email address will not be published. Required fields are marked *