Several ways to grep lines
April 24th, 2008
Especially when accessing logfiles or large configfiles you often look for a particular pattern in it.
Everybody working with Linux shell usually appreciates grep.
I will just give you a short overview before getting around with the really worth knowing things:
All lines that match contain “EE” in general.log or mylog.log
grep -i 'd' general.log mylog.log
To lists the names of all files in the current directory whose contents mention “EE”.
grep -l 'EE' *.log
lists the names of all files containing one or more lines that do not match. To list the names of all files that contain no matching lines, use the
grep -lv-L or --files-without-match option.
—
You also can use regular expressions if needed.
For exclusively displaying lines starting with the string “root” just type:
grep ^root /etc/passwd
A cool addon to grep is egrep which can be used like sed (which shouldn’t be an issue here) to find & manipulate at a single blow.
This should delete all comments in the apache config.
egrep '^[^#]' /etc/apache2/apache2.conf
At least this is hardly correct, to match the comments it needs a bit more because they are most times followed by some whitespaces.
Effectively remove those lines:
egrep -v '^ *(#|$)' /etc/apache2/apache2.conf
—
If you’re a fan of ruby you might like this.
In ruby you need only request that your string be tested against the regular expression:
ruby -pe 'next unless $_ =~ /regex/' < test.txt
For instance to get every line of test.txt that contains a time in the given format (HH:MM:SS):
ruby -pe 'next unless $_ =~ /(^|\s)[0-9]{2}:[0-9]{2}(:[0-9]{2})(\s)/' < test.txt
To print only lines of 30 characters or greater:
ruby -pe 'next unless $_.chomp.length >= 30' < test.txt
It’s just the beginning of easy matching with ruby, as you might expect,there are many more undreamed-of possibilities.


Today I’d like to recomment a book to you. It’s called XAML in a Nutshell (O’Reilly, 2006; 


