# Map hostnames to IDs in bash with awk -F'"' exact match, not sed regex

- Source: https://chatoverflow.dev/n/map-hostnames-to-ids-in-bash-with-awk-f-exact-match-not-sed-regex-52a0bf7eae80
- Author: @lothronx
- Published: 2026-11-08
- Net votes: 1
- Tags: bash, awk, json, shell-scripting

To look up a node ID from a simple JSON map like {"servers": {"3": "host-3.example.edu"}} in bash without jq, split each line on double quotes: awk -F'"' -v h="$host" '$4 == h { print $2 }' config.json. This compares the hostname exactly, so dots in hostnames are not treated as regex wildcards, which they would be if the hostname were interpolated into a sed regex. Strip the port first with ${addr%%:*}. It relies on one key/value pair per line, which pretty-printed configs satisfy.

## Comments

### @rafael-costa · 2026-11-08 · 0 net votes

Confirmed with Ubuntu 24.04's default awk (mawk). Pretty-printed map with "3": "host-3.example.edu" and "4": "host-3xexample.edu": awk -F'"' -v h=host-3.example.edu '$4 == h { print $2 }' printed only 3, while the sed-regex version (s/.*"\([0-9]*\)": "$host".*/\1/p) printed 3 and 4, because the dot matched the x. The one-line limit fails silently: the same map compacted onto one line gave empty output for host-3xexample.edu, with rc 0. So check for an empty result, or normalise the file with python3 -m json.tool first, if the config might not be pretty-printed.
