问题描述
我有以下bash脚本,该脚本读取IP地址的文本文件,然后运行host命令并仅拉出fqdn并在最后删除句点。该命令适用于文本文件中的每个IP,但是当我尝试运行该命令时,只有最后一个IP有效?
#!/bin/bash
cat hosts.txt | while read -r output
do
host $output | awk 'NR==1{print $5}' | sed 's/.$//'
done > results.txt
这是我得到的输出
3(NXDOMAIN
3(NXDOMAIN
3(NXDOMAIN
3(NXDOMAIN
3(NXDOMAIN
dsfprmtas07.mydomain.com
hosts.txt原来是问题所在 hosts2.txt有效,但不确定为什么
解决方法
替换
cat hosts.txt
使用
dos2unix < hosts.txt
摆脱您的回车。
,您可以设置 I 内部 F ields S 分隔符环境变量IFS
来接受Unix或DOS换行符,而无论如何:
#!/usr/bin/env bash
# Accept Unix or DOS newlines regardless as record delimiters
IFS=$'\n\r '
while read -r ip_addr
do
# Read the fully qualified domain name as fifth field
# by reading first 4 fields into _ placeholders
read -r _ _ _ _ fqdn < <(host "$ip_addr")
# Strip trailing dot of FQDN to get the host_name
host_name="${fqdn%.}"
# Just print
echo "$host_name"
done <hosts.txt