Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep for beginning and end of line?

Tags:

grep

I have a file where I want to grep for lines that start with either -rwx or drwx AND end in any number.

I've got this, but it isnt quite right. Any ideas?

grep [^.rwx]*[0-9] usrLog.txt 
like image 780
texasCode Avatar asked Jan 25 '11 23:01

texasCode


People also ask

How do you use grep to find lines ending with the pattern?

Matching the lines that end with a string : The $ regular expression pattern specifies the end of a line. This can be used in grep to match the lines which end with the given string or pattern. 11. -f file option Takes patterns from file, one per line.

Can you use regex with grep?

GNU grep supports three regular expression syntaxes, Basic, Extended, and Perl-compatible. In its simplest form, when no regular expression type is given, grep interpret search patterns as basic regular expressions. To interpret the pattern as an extended regular expression, use the -E ( or --extended-regexp ) option.

How do you grep 5 lines before and after?

You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines.


1 Answers

The tricky part is a regex that includes a dash as one of the valid characters in a character class. The dash has to come immediately after the start for a (normal) character class and immediately after the caret for a negated character class. If you need a close square bracket too, then you need the close square bracket followed by the dash. Mercifully, you only need dash, hence the notation chosen.

grep '^[-d]rwx.*[0-9]$' "$@" 

See: Regular Expressions and grep for POSIX-standard details.

like image 92
Jonathan Leffler Avatar answered Sep 17 '22 13:09

Jonathan Leffler