Monday, April 11, 2022

[SOLVED] grep or sed or awk + match WORD

Issue

I do the following in order to get all WORD in file but not in lines that start with "//"

  grep -v "//"  file | grep WORD

Can I get some other elegant suggestion to find all occurrences of WORD in the file except lines that begin with //?

Remark: "//" does not necessarily exist at the beginning of the line; there could be some spaces before "//".

For example

 // WORD
 AA WORD
         // ss WORD

Solution

grep -v "//"  file | grep WORD

This will also exclude any lines with "//" after WORD, such as:

WORD // This line here

A better approach with GNU Grep would be:

 grep -v '^[[:space:]]*//' file | grep 'WORD'

...which would first filter out any lines beginning with zero-or-more spaces and a comment string.

Trying to put these two conditions into a single regular expression is probably not more elegant.



Answered By - Johnsyweb
Answer Checked By - Cary Denson (WPSolving Admin)