Stacker
Stacker

Reputation: 157

Limit grep to first match per line

I'm trying to grep for all lines that have the letter a before the first period in the line.

Here's an example file:

test123a.hello
example.more-test-a.xyz
stacka.tester.this
nothing.nothing.nothing

In the example above, I'd want to grep these 2 lines:

test123a.hello
stacka.tester.this

This is what I've tried:

grep ".*a\." test.txt

That is getting the 2 lines I want, but it's also getting this line, which I don't want, be the a is in front of the second period, not the first one:

example.more-test-a.xyz

How do I limit it to just get the lines with a before the first period?

Upvotes: 1

Views: 2110

Answers (3)

Sundeep
Sundeep

Reputation: 23667

$ grep '^[^.]*a\.' test.txt
test123a.hello
stacka.tester.this
  • ^ to restrict matching at start of line
  • [^.]* to match any character other than . character, zero or more times
  • a literally match character a
  • \. literally match character .


You can also use awk here, which is more suited for field based processing

$ # 'a' as last character for first field
$ awk -F'.' '$1 ~ /a$/' test.txt
test123a.hello
stacka.tester.this

$ # 'a' as last character for second field
$ awk -F'.' '$2 ~ /a$/' test.txt
example.more-test-a.xyz

Upvotes: 2

William Prigol Lopes
William Prigol Lopes

Reputation: 1889

You can try [EDITED]

grep ".*a." test.txt | grep -v "\([^a]\.\)\{1,\}.*a."

This will do your first grep and denies anything with "a." preceded by a dot.

Upvotes: 0

none
none

Reputation: 139

if you feel many output, you can try

grep ".*a." test.txt | less

Upvotes: 0

Related Questions