1

我正在解析提取字符串的结果。我的问题是处理第一个元素后执行停止。

这是我的代码:

#!/bin/bash

SCAN_RESULT=$(arp-scan --ignoredups --interface=$1 --localnet)
HEADER_REMOVED=$(echo "$SCAN_RESULT" | sed '1,2d')
NO_HEADER_LINE_COUNT=$(echo "$HEADER_REMOVED" | wc -l)
CAPTURED_DEVICE_INFO=$(echo "$HEADER_REMOVED" | sed $(expr $NO_HEADER_LINE_COUNT - 2),"$NO_HEADER_LINE_COUNT"d)
DATA=$(echo "$CAPTURED_DEVICE_INFO" | sed 's/[\t]/;/g')

DATA_LINE_COUNT=$(echo "$DATA" | wc -l)

echo -n '['
for ((i=0; i<$DATA_LINE_COUNT; i++))  # stops execution after 1st cycle
do
    EXTRACTED_DATA=$(echo "$DATA" | sed $(expr "$i" + 1)'!d')
    echo -n '{'
    COMMA_INNER=''
    for i in {1..3}
    do
        echo -n "$COMMA_INNER"      
        case $i in
            1) echo -n '"ip":' ;;
            2) echo -n '"mac":' ;;
            3) echo -n '"manufacturer":' ;;
        esac
        echo -n '"'
        echo -n $(echo $EXTRACTED_DATA | cut -d ';' -f$i)
        echo -n '"'
        COMMA_INNER=','
    done
    echo -n '}'
done
echo -n ']'

这是 arp-scan 的输出字符串:

Interface: eth0, datalink type: EN10MB (Ethernet)
Starting arp-scan 1.8.1 with 16 hosts (http://www.nta-monitor.com/tools/arp-scan/)
192.168.0.1     20:aa:4b:c0:22:78       (Unknown)
192.168.0.5     48:5b:39:a0:60:ba       ASUSTek COMPUTER INC.
192.168.0.7     04:7d:7b:7d:c4:e9       (Unknown)

5 packets received by filter, 0 packets dropped by kernel
Ending arp-scan 1.8.1: 16 hosts scanned in 0.819 seconds (19.54 hosts/sec). 3 responded

这是我想作为 JSON 处理和回显的字符串(来自 arp-scan)

192.168.0.1     20:aa:4b:c0:22:78       (Unknown)
192.168.0.5     48:5b:39:a0:60:ba       ASUSTek COMPUTER INC.
192.168.0.7     04:7d:7b:7d:c4:e9       (Unknown)

这是示例输出:

[{"ip":"192.168.0.1","mac":"20:aa:4b:c0:22:78","manufacturer":"(Unknown)"}]

我做错了吗?

4

3 回答 3

1
arp-scan --ignoredups --interface=$1 --localnet | {
  read; read    # Discard the first two header lines
  printf "["
  comma=''
  while read ip mac manufacturer; do
    printf '%s{"ip":"%s", "mac":"%s", "manufacturer":"%s"},' "$comma" "$ip" "$mac" "$manufactuer"
    comma=','
  done
  printf "]\n"
}
于 2013-10-22T17:53:52.627 回答
1

您正在使用

  • 两个循环的相同变量 ( i) 和
  • cut用(使用' '而不是)分割行时错误的分隔符';'

但是,chepner 的解决方案应该要好得多。

于 2013-10-22T18:36:54.677 回答
1

如果我正确理解了你的问题(一个很大的if,它非常不清楚),这将做到:

sed '1,2d;s/^/[{"ip":"/;s/  */","mac":"/;s/  */","manufacturer":"/;s/$/"}]/'
于 2013-10-22T21:18:17.270 回答