user2922456
user2922456

Reputation: 391

Grep square brackets, unix bash

I need to grep on txt file, for instance this is the file

[Hey my][aaaaaaa]
bla bla bla
bla bla

I want the first line where the words "Hey my" apears

So this is my code:

grep "Hey my" file.txt | head -n 1

but this will give all the first line, I need the first square brackets only

How I do that..?

Upvotes: 1

Views: 477

Answers (2)

ryanpcmcquen
ryanpcmcquen

Reputation: 6475

Use cut:

grep "Hey my" test | cut -d[ -f1-2

This will work on almost any Unix (Mac OS, BSD) or Linux.

Upvotes: 3

Eric Renouf
Eric Renouf

Reputation: 14520

You may want to look at the -o flag with GNU grep. It will show only the parts of the line that match. Also, -m will stop after some number of matches, so you could do those 2 commands as

grep -m 1 -o "Hey my" file.txt

Which will just give you "Hey my" as a result.

If you want the brackets too, since brackets define character classes in regex you probably want to add the -F flag to tell grep not to use regex like

grep -m1 -oF "[Hey my]" file.txt

Upvotes: 2

Related Questions