awk 变量传递问题

awk 变量传递问题

这是我编写的用于解析 DNS 并输出到文件的代码。有没有办法完全放弃循环while,只写入awk?它运行完美,但似乎非常繁琐和低效,25k 行 IP 大约需要 10 分钟。如果需要清晰度,很乐意详细说明脚本。

#!/bin/bash

while read line; do
  echo -en " ${startCount} / ${endCount} IPs resolved\r"
  ip=$(echo ${line} | cut -d "," -f1)
  col2=$(nslookup ${ip} | fgrep "name" | sed -e 's/\t/,/g' -e 's/name = //g' -e 's/.uncc.edu.//g' | cut -d "," -f2)
  if [[ ! -z ${col2} ]]; then
    echo "${line}" | awk -F"," -v var="${col2}" '{print $1","var","$2","$3","$4","$5","$6}' >> ${outFile}
  else
    echo "${line}" | awk -F"," '{print $1",""UNRESOLVED"","$2","$3","$4","$5","$6}' >> ${outFile}
  fi
  ((startCount++))
done < ${1}

答案1

尝试这个:

gawk -F, '
    # spawns nslookup as a coprocess, passes the IP into its stdin
    # then reads the output of the coprocess to find the hostname
    function get_name(ip,      line, name) { 
        name = "UNRESOLVED"
        print ip |& "nslookup"
        close("nslookup", "to")
        while (("nslookup" |& getline line) > 0) {
            if (match(/name =(.+)\.uncc\.edu\./, line, m)) 
                name = m[1]
        }
        close("nslookup")
        return name
    }
    { print $1, get_name($1), $2, $3, $4, $5, $6 }
' "$1" > "$outfile"

參考文獻:https://www.gnu.org/software/gawk/manual/html_node/Two_002dway-I_002fO.html

相关内容