简体   繁体   中英

Match a string in a file and print entire value using sed or awk

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.

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

使用perl:

perl -lne 'print $1 if(/(login[\S]+\s).*/)'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM