[英]Linux - Find a string and get the next section
If I have a string like "name":"tempname","department":"tempdept", I want to search for the value for "department" which is "tempdept". 如果我有一个类似“ name”:“ tempname”,“ department”:“ tempdept”的字符串,我想搜索“ tempdept”的“ department”值。 So if "department" exists, I need just the value returned.
因此,如果“部门”存在,我只需要返回的值即可。 The length of the string that is searched can be very long.
搜索的字符串的长度可能会很长。 Is this possible using sed/awk, can you please help?
是否可以使用sed / awk,请您帮忙?
I tried the following, but it returns the whole string. 我尝试了以下操作,但是它返回了整个字符串。 I am searching for department here.
我在这里寻找部门。
echo $data | sed 's/\(\"department\":\)\(.*\"\)/\2/'
Some simple solutions: 一些简单的解决方案:
echo "$data" | tr , \\n | awk -F: '$1 ~ /^department$/{ print $2 }'
or 要么
echo "$data" | awk -F: '$1 ~ /^department$/{ print $2 }' RS=,
Your solution just need minor modifications: 您的解决方案只需要稍作修改:
echo "$data" | tr , \\n | sed -n 's/"department":\(.*\)/\2/p'
or 要么
echo "$data" | tr , \\n | sed -n '/"department":/s///p'
See if this does it for you: 看看这是否适合您:
sed -ne '/"department"/{s/^.*"department":"\([^"]*\).*/\1/;p;}'
Example: 例:
echo '"name":"tempname","department":"tempdept"' | sed -ne '/"department"/{s/^.*"department":"\([^"]*\).*/\1/;p;}'
tempdept
If you need to retain the double quotes, just add them back in during the replacement: 如果需要保留双引号,只需在替换期间将其重新添加:
sed -ne '/"department"/{s/^.*"department":"\([^"]*\).*/"\1"/;p;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.