提问人:dckiller 提问时间:11/15/2023 最后编辑:dckiller 更新时间:11/17/2023 访问量:97
AWK 打印子 IF ELSE IF [关闭]
AWK print substr IF ELSE IF [closed]
问:
我在理解如何使用 substr 制作 IF 时遇到了问题。
#!/bin/bash
awk -F"[= ]" 'NR==FNR{a[$2]=$3" "$4;next} ($2 in a) {print substr($1,1,9)" "substr($1,11,8)" "($3<1 ? "home":"not_home"),a[$2]}' dhcp.leases associations.dto
dhcp.leases
1700005989 d9:dc:b1:f0:2b:7d 192.168.1.2 Computer-Test 01:d9:dc:b1:f0:2b:7d
0 fa:65:e2:2e:24:dc 192.168.1.54 Phone-Aurel *
0 f3:de:8c:ae:b1:f3 192.168.1.23 * 01:f3:de:8c:ae:b1:f3
assosiations.dto
WifiAP-01_phy0-ap0=d9:dc:b1:f0:2b:7d=10
WifiAP-02_phy1-ap0=fa:65:e2:2e:24:dc=0
WifiAP-01_phy2-ap0=f3:de:8c:ae:b1:f3=1
结果:
WifiAP-01 phy0-ap0 not_home 192.168.1.2 Computer-Test
WifiAP-02 phy1-ap0 home 192.168.1.54 Phone-Aurel
WifiAP-01 phy2-ap0 not_home 192.168.1.23 *
预期结果
WifiAP-01 2.4ghz not_home 192.168.1.2 Computer-Test
WifiAP-02 IOT home 192.168.1.54 Phone-Aurel
WifiAP-01 5ghz not_home 192.168.1.23 *
我现在想与声音进行比较$3<1 ? "text": "text1"
substr($1,11,8) if ==phy0 return text else if ==phy1 return text1 else retrun text2
awk -F"[= ]" 'NR==FNR{a[$2]=$3" "$4;next} ($2 in a) {print substr($1,1,9)" "(if (substr($1,11,8)==phy0-ap0) "text" else if (substr($1,11,8)==phy1-ap0) "text1" else "text2")" "($3<1 ? "home":"not_home"),a[$2]}' dhcp.leases associations.dto
错误出在这一部分。
"(if (substr($1,11,8)==phy0-ap0)"text" else if (substr($1,11,8)==phy1-ap0)"text1" else "text2")"
^ 语法错误
这很好。
(substr($1,11,8)=="phy0-ap0" ? "IOT":(substr($1,11,8)=="phy1-ap0" ? "2.4ghz":"5ghz"))
这不起作用语法错误
(s=substr($1,11,8); (s=="phy0-ap0" ? "IOT":(s=="phy1-ap0" ? "2.4ghz":"5ghz")))
如果还存在错误,则
(if (substr($1,11,8)=="phy0-ap0") "IOT" else if (substr($1,11,8)=="phy1-ap0") "2.4ghz" else "5ghz")
我的代码正在进行中
#!/bin/bash
string=$(awk -F"[= ]" 'NR==FNR{a[$2]=$3" "$4;next} ($2 in a) {print substr($1,1,9)" "substr($1,11,8)" "$2" "$3" "($3<1 ? "home":"not_home"),a[$2]}' dhcp.leases associations.dto)
jq --slurp --raw-input 'split("\n")[:-1] | map([ split(" ")[] ]) | map({
source: .[0],
source_ssid: .[1],
mac: .[2],
idx: .[3],
ip: .[5],
hostname: .[6],
location_name: .[4]
})' <<< "$string"
我用于发送给家庭助理的测试代码
#!/bin/bash
# Home Assistant Config
server="MYADRESSEHOMEASSITANT"
token="MYTOKEN"
body='{"dev_id":"d9dcb1f02b7d","host_name":"Google-Home-Noham","mac":"d9:dc:b1:f0:2b:7d","location_name":"home","attributes":{"source_type":"WifiAP-01","source_ssid":"2.4ghz","mac":"d9:dc:b1:f0:2b:7d","ip":"192.168.1.2","disconnected_idx":"0"}}'
# Publish to HA with token
curl -X POST -H "Authorization: Bearer $token" \
-H "Content-Type: application/json" \
-d "$body" \
"$server"/api/services/device_tracker/see
答: 暂无答案
评论