我在日志文件中有关于发送代码的字符串,如:
<timestamp> INFO [Response--22] Code [00000000] Code was sent to [+0000002345]
你能帮我解析一下使用BASH将代码值(8chars)放到变量中吗? 谢谢你的帮助。
答案 0 :(得分:0)
您可以使用sed来提取值:
sed 's/.*Code *\[\([0-9]*\)].*/\1/' <<<"<timestamp> INFO [Response--22] Code [00000000] Code was sent to [+0000002345]"
00000000
如果该行在文件中,您可以执行sed '...' filename
。要将输出存储到变量,可以执行x=$(sed '...' filename)
。
答案 1 :(得分:0)
如果我理解你的要求:
$ x="<timestamp> INFO [Response--22] Code [00000000] Code was sent to [+0000002345]"
$ echo "$x" | sed -r 's/.*(Code )\[([0-9]+)\].*/\1= \2/'
Code = 00000000
答案 2 :(得分:0)
sed -r 's/(.*)(Code )\[([0-9]+)\](.*)/code = \3/'
<强>输出:强>
sdlcb@ubuntu:~/AMD_C$ echo "<timestamp> INFO [Response--22] Code [00000000] Code was sent to [+0000002345]" | sed -r 's/(.*)(Code )\[([0-9]+)\](.*)/code = \3/'
code = 00000000
答案 3 :(得分:0)
x='<timestamp> INFO [Response--22] Code [00000000] Code was sent to [+0000002345]'
read -a fields <<<"$x"
code=${fields[4]//[][]/}
echo "code=$code"