Finding a string in a file

Hello All,

I have a text file, i want to search for a string in it and the string is repeated multiple times in a file i want to get the first occurence of the string in a variable.

the content of file is like:

I want to grepthe first occurance of "Configuration flow done" and store the result in a variable,
I am currently doing

var=`cat "filename" | grep "Configuration flow done"`

,
Here var shows var=2012-12-04 13:48:28 minor dmsc: Configuration flow done for "919852104962"

but what i want is:
var=2012-12-04 13:00:15 minor dmsc: Configuration flow done for "919852104962"

Need help....thanks in advance

can you try something like this.

cat filename | grep -i 'Configuration flow done' | head -1
1 Like

One with sed

$ sed -n "/Configuration flow done/{p;q;}" filename
2012-12-04 13:00:15 minor dmsc: Configuration flow done for "919852104962"

Some grep's also have an option (i.e. -m NUM) to exit after the specified number of matches.

1 Like

Thanks Guys :b:

Try it without the cat

var=`grep -i 'Configuration flow done' filename | head -1`

Robin
Liverpool/Blackburn
UK

1 Like

with awk

var=$(awk '/Configuration flow done/ {print;exit}' filename)

the exit makes awk exit after first find.

2 Likes

Thank You All
I also got an option

cat filename | grep -m1 "Configuration flow done"

It also worked

You should use

grep -m1 "Configuration flow done" filename
var=$(grep -m1 "Configuration flow done" filename)

cat not needed.