Pratik Kumar
Pratik Kumar

Reputation: 67

grep words from commented file

I want to grep a particular command/word say int from a file.
But I want to eliminate all those lines which are commented.
(I want to ignore if int is after # ).

My file content :

int a
def
abc int
adbc asdfj #int
abc # int
# int abc
abc int #
int # abc

I want output as :

int a
abc int
abc int #
int # abc 

I tried using grep -e "int" | grep -v -e "#" . But problem is int # abc is also getting eliminated.

Upvotes: 3

Views: 200

Answers (6)

Claes Wikner
Claes Wikner

Reputation: 1517

awk '/abc int/ || /^int/' file
int a
abc int
abc int #
int # abc

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203491

This MIGHT be what you want, using GNU awk for word boundaries:

$ awk -F'#' '$1~/\<int\>/' file
int a
abc int
abc int #
int # abc

depending on what you want to do if int appears both before and after the #.

Upvotes: 0

Tiago Lopo
Tiago Lopo

Reputation: 7959

Can you use perl? if so it's a piece of cake:

perl -ne '/int/ && !/#(.*?)int/ && print' file 
int a
abc int
abc int #
int # abc

Another alternative is to use -P for grep:

grep -Pv '#.*?int' file | grep int
int a
abc int
abc int #
int # abc

If you want to ignore all comments it can be done with sed :

grep -Pv '#.*?int' file | grep int | sed -re 's/#.*//g'
int a
abc int
abc int 
int 

Using variable instead of "int":

i="int"; grep -Pv "#.*?$i" file | grep "$i"
int a
abc int
abc int #
int # abc

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246807

I see some deleted answers with this valid single-regex answer: grep '^[^#]*\<int\>'

grep '^[^#]*\<int\>' <<END
int a
def
abc int
adbc asdfj #int
abc # int
abc int #
int # abc
print abc  # int -- should not see this line
END
int a
abc int
abc int #
int # abc

Do you have int on both sides of the #? What should you do in that case?

$ echo "int foo # int bar" | grep '^[^#]*\<int\>'
int foo # int bar

To see if "int" is used in the file, use grep's -q option:

if grep -q '^[^#]*\<int\>' file; then 
    echo "I have an 'int'"
else
    echo "No int here"
fi

To pass the word as a parameter, you need double quotes, and escape the backslashes:

type="int"
if grep -q "^[^#]*\\<$type\\>"; then ...

Upvotes: 1

Jotne
Jotne

Reputation: 41456

Using awk you can do:

awk '/int/ && !/#.*int/' file
int a
abc int
abc int #
int # abc

This will get all line that contains int but ignore if int comes after # (comment)

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

And the one through sed,

$ sed '/#.*int/d' file
int a
abc int
abc int #
int # abc

It just deletes the line in which the string int is just after to # symbol.

Upvotes: 0

Related Questions