BASH SPLIT STRING成自己的OUTPUT

时间:2014-06-25 21:27:10

标签: string bash split

我该怎么分裂这个字符串

22:45:47.349293 00:00:00:00:00:00> 20:cf:30:39:60:69,ethertype IPv4(0x0800),长度342:192.168.0.1> 192.168.0.100.68:BOOTP / DHCP,回复,长度300

像这样的一行

TIME FIRSTMACADDRESS FIRSTIP

22:45:47 00:00:00:00:00:00 192.168.0.1

我的实际结果是

时间:22:45:47

MAC:00:c0:26:00:bc:14 IP:192.168.0.1

使用此代码

    cat $TEMPDATA | while read line
    do
    if [ "$line" != "" ]; then

    set -- $line

    echo TIME: "$line" | awk -F '[.]' '{print $1}'
    echo MAC: "$2" IP: "$10"
    echo



    fi

    done

1 个答案:

答案 0 :(得分:0)

这可以在bash中轻松完成。这是快速有效的:

#!/bin/bash

string="22:45:47.349293 00:00:00:00:00:00 > 20:cf:30:39:60:69, ethertype IPv4 (0x0800), length 342: 192.168.0.1 > 192.168.0.100.68: BOOTP/DHCP, Reply, length 300"

time="${string%%.*}"
tmp="${string#* }"
mac="${tmp%% *}"
tmp="${string%\ \>*}"
ip="${tmp##*\:\ }"

echo "time: '$time', mac: '$mac', ip: '$ip'"

输出:

time: '22:45:47', mac: '00:00:00:00:00:00', ip: '192.168.0.1'