[英]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
进行搜索,输出应该是
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. 如果
login_name
不是第二个字段,则不会打印。
How can i search for a string in any position and then print the result ? 如何在任意位置搜索字符串,然后打印结果?
Thanks in advance. 提前致谢。
You could use grep, 您可以使用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, 通过sed
$ echo 'name=sandeep login_name=sn003 version=3.0 rel_no=456.....' | sed 's/.*\([^ ]*login[^ ]*\).*/\1/'
login_name=sn003
OR 要么
Through awk, 通过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).*/)'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.