tuna
tuna

Reputation: 931

How to search for whole lines

My intention is to determine if a whole line is present in a config file. Here is an example:

ports.conf:

#NameVirtualHost *:80
NameVirtualHost *:80

Now I want to search for NameVirtualHost *:80 but NOT for #NameVirtualHost *:80!

My first thought about this was, of course, to using grep. Like this:

grep -F "NameVirtualHost *:80" ports.conf That is giving me boths lines which is not what I want. My second thought was to use regex like this: grep -e "^NameVirtualHost \*:80" ports.conf. But obviously now I have to treat with escaping special characters line *

This might be not a big deal but I want to pass individual search strings in and dont wanna bother with escaping strings as I am using my script.

So my question is: How do I escape special characters? or How can I achieve the same result with different tools?

Upvotes: 1

Views: 79

Answers (3)

Daniël W. Crompton
Daniël W. Crompton

Reputation: 3518

The quickest way I can think of to keep your regexp simple is

grep -F "NameVirtualHost *:80" ports.conf | grep -v "^#\|^\/\/"

Upvotes: 0

bartimar
bartimar

Reputation: 3534

Use printf escaping

printf '%q' 'NameVirtualHost *:80'

All together

grep -e "^`printf '%q' 'NameVirtualHost *:80'`$" test

Or

reg="NameVirtualHost *:80"
grep -e "^`printf '%q' "$reg"`$" test

Upvotes: 1

Ulrich Schmidt-Goertz
Ulrich Schmidt-Goertz

Reputation: 1116

grep has an option -x which does exactly that:

-x, --line-regexp
          Select only those matches that exactly match the whole line.  (-x is specified by POSIX.)

So if you change your first command to grep -Fx "NameVirtualHost *:80" ports.conf, you get what you want.

Upvotes: 4

Related Questions