-1

I am trying to extract the value associated with string, but need an optimal way.

name=sandeep login_name=sn003 version=3.0 rel_no=456....

The above text is stored in a file.
I am trying to search for a part of string and then print the entire value.

Say I need to search using login and output should be

login_name=sn003

I have tried the command

cat filename | awk -F" " '{print $2}'

If login_name is not the second field this will not print though.
How can i search for a string in any position and then print the result ?

Thanks in advance.

sandeep nagendra
  • 422
  • 5
  • 15
  • possible duplicate of [How to extract string following a pattern with GREP, REGEX or PERL](http://stackoverflow.com/questions/5080988/how-to-extract-string-following-a-pattern-with-grep-regex-or-perl) – tripleee Jan 28 '15 at 13:10

2 Answers2

2

You could use grep,

$ echo 'name=sandeep login_name=sn003 version=3.0 rel_no=456.....' | grep -o '[^ ]*login[^ ]*'
login_name=sn003

[^ ]* matches any character but not of a space, zero or more times.

OR

Through sed,

$ echo 'name=sandeep login_name=sn003 version=3.0 rel_no=456.....' | sed 's/.*\([^ ]*login[^ ]*\).*/\1/'
login_name=sn003

OR

Through awk,

$ echo 'name=sandeep login_name=sn003 version=3.0 rel_no=456.....' | awk '{for(i=1;i<=NF;i++){if($i~/login/){print $i}}}'
login_name=sn003
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

use perl:

perl -lne 'print $1 if(/(login[\S]+\s).*/)'
Vijay
  • 65,327
  • 90
  • 227
  • 319