Parsing substrings into shell variables in bash [d

2019-09-14 07:31发布

This question already has an answer here:

We got the following input:

[18:51:10] [Server thread/INFO]: Tester121 entered area ~ Wilderness - (PvP) ~

We'd like to interpret the input and define different variables.

[$time] [Server thread/INFO]: $player entered area ~ $area - (PvP) ~

The results should be:

time="18:51:10"
player="Tester121"
area="Wilderness"

I am new to stackoverflow, feel free to comment so that I can improve my how to ask skills.

标签: bash shell
1条回答
对你真心纯属浪费
2楼-- · 2019-09-14 07:38

The =~ operator in [[ ]] evaluates a regex in POSIX ERE format, and assigns the resulting match groups to the array BASH_REMATCH.

re='^\[([[:digit:]:]+)\] \[Server thread/INFO\]: ([^[:space:]]+) entered area ~ ([^[:space:]]+) - [(]PvP[)] ~'
line='[18:51:10] [Server thread/INFO]: Tester121 entered area ~ Wilderness - (PvP) ~'

if [[ $line =~ $re ]]; then
  time=${BASH_REMATCH[1]}
  player=${BASH_REMATCH[2]}
  area=${BASH_REMATCH[3]}
fi
查看更多
登录 后发表回答