使用bash获取部分字符串

时间:2014-10-24 08:08:20

标签: linux bash parsing git-bash

我在日志文件中有关于发送代码的字符串,如:

 <timestamp> INFO   [Response--22] Code [00000000] Code was sent to [+0000002345]

你能帮我解析一下使用BASH将代码值(8chars)放到变量中吗? 谢谢你的帮助。

4 个答案:

答案 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"