Home > Enterprise >  grep for word, whitespace word
grep for word, whitespace word

Time:10-09

How does one do that in grep 3.1?

Searching for whitespace, then a word, then more whitespace works just fine, but grepping for a word, whitespace and then another word fails.

$ grep '[[:space:]]replication[[:space:]]' pg_hba.conf
local   replication     all                                     trust
host    replication     all             127.0.0.1/32            trust
host    replication     all             ::1/128                 trust

$ grep 'host[[:space:]]replication' pg_hba.conf
$

The output of the first command demonstrates that there are lines in pg_hba.conf with the words host and replication.

My goal is to find the lines which have host, some whitespace and then the word replication. Not, IOW, the line with "local" in it.

CodePudding user response:

1st solution: With your shown samples please try following grep code. There are 2 important things you are missing there, 1st: We better use -E to enable ERE and 2nd: we need to put after [[:space:]] since its NOT 1 space occurrence its more than that. So your command would become like:

grep -E 'host[[:space:]] replication' pg_hba.conf

OR in case you want to match for exact word host then use like:

grep -E '(^|[[:space:]] )host[[:space:]] replication' pg_hba.conf


2nd solution: With awk also you can try like following, considering if host is always coming in starting of line and replication string is always 2nd field/column in your Input_file.

awk '$1=="host" && $2=="replication"' Input_file
  • Related