user3578925
user3578925

Reputation: 941

Regular expressions matching exactly one line

I am pretty new to regular expressions. I've been trying to use 'grep' alongside with regular expressions to extract a line from a file. I thought some of you might help:

My file has the lines:

c total length of integration
ntotal= 0
c total number of updates
ntotal= 20
c total number of outputs 
ntotal= 10

So I was wondering how do I extract the first occurrence of 'ntotal= 0'

I tried with grep ^c.*tot.*\n? 'filename' , but that did not work.

Any ideas?

Regards,

Abedin

Upvotes: 1

Views: 147

Answers (2)

Jotne
Jotne

Reputation: 41460

To get the first ntotal you can use awk like this:

awk '/ntotal/ {print $0;exit}' file
ntotal= 0

It search for ntotal, if found, print the line and then exit.

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

grep has a flag -m that sets the maximum number of occurrences to match,

thus

grep -m 1 -P '^ntotal *= *[0-9]+$' < filename

Starting the expression with ^ means that this is the start of a line, $ means the end of the line. The -P flag means that extended regular expression patterns are enabled (Perl style).

I've added * so that there is an arbitrary amount of spaces between ntotal and = allowed (zero or more).

< filename means that you use the content of the file called filename as input.

Upvotes: 2

Related Questions