gthm
gthm

Reputation: 1948

How to handle "-" in grep?

Its been asked several times but its not clear to me yet.

I have the following text in a file ( data.txt, tab delimeted ):

ABC    12
ABC-AS    14
DEF    18
DEF-AS    9

Now I want to search for ABC and DEF, but not ABC-AS, DEF-AS as a result.

grep -w ABC data.txt

Output:

grep -w ABC data.txt
ABC
ABC-AS


grep --no-group-separator -w "ABC" data.txt      
ABC
ABC-AS

grep --group-separator="\t" -w "ABC" data.txt
ABC
ABC-AS

Upvotes: 0

Views: 172

Answers (2)

Benoît Zu
Benoît Zu

Reputation: 1287

With a regex

grep -E "(ABC|DEF)[^\-]" data.txt

Details

(ABC|DEF): Match "ABC" or "DEF"

[^\-]: Anything except "-"

Output

ABC    12
DEF    18

Upvotes: 1

MyCuky LoVe
MyCuky LoVe

Reputation: 76

Try this, which select only those matches that exactly match the whole line

grep --line-regexp "ABC" data.txt

Upvotes: 1

Related Questions