我是 zshell 的新手,正在尝试使用关键字作为分隔符来拆分字符串。输出来自 netfilter,并不总是在固定位置,因此我需要按我感兴趣的关键字进行拆分。
我找到了一种可行的方法,但似乎应该有一种更简单的方法来实现。有什么想法吗?
line="[Thu Jul 23 12:29:50 2015] IN=eth0 OUT= SRC=10.1.1.17 DST=10.101.11.1 PROTO=TCP SPT=46286 DPT=1113 SYN URGP=0 "
# this returns a substring starting from 'SRC=' to the end
tmp=${(MS)line##SRC=*}
# use the first element returned in the substring
src=$tmp[(w)1]
echo "src is $src"
最佳答案
要解析单个关键字,我会使用正则表达式匹配 =~
conditional operator .
if [[ $line =~ [[:space:]]SRC=[^[:space:]]+ ]]; then
echo src is $MATCH[6,$#MATCH]
else
echo >&2 No SRC=
fi
要解析多个关键字,我会使用 parameter expansion constructs 拆分字符串减去空格处的时间戳并将输出存储在关联数组中。
timestamp=${${line%%\]*}##*\[}
typeset -A info
for x in ${=line#*\]}; do
if [[ $x = *=* ]]; then
info[${x%%=*}]=${x#*=}
else
info[$x]=
fi
done
echo src is $info[SRC]
关于linux - 如何在 zshell 中以关键字拆分字符串并保存结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31594453/