Find pattern in file

Problem

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



Solution

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


grep "pattern" filename



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



Reference

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



Leave a Reply

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