我有一个带有 ipaddress.txt 输入文件的 bash 脚本,我想将其用于 csv 文件。我想找到 IP,然后显示 A 列的值(目前)。我可能想显示两列或三列。我使用的脚本找到了 IP,但没有打印 A 列中的值。要注意:如果它对答案有帮助,IP 地址位置是 csv 文件的第 16 列或 P 列。
#!/bin/bash
# Read input file with IP addresses
input_file="ipaddress.txt"
while IFS= read -r ip_address; do
# Search for IP address in CSV file
csv_file="network-data.csv"
grep -q "$ip_address" "$csv_file"
# Print result
if [ $? -eq 0 ]; then
echo "$ip_address found in $csv_file"
awk -F, -v "$ip_address"= '$16 == ip { print $1 }' "$csv_file"
else
echo "$ip_address not found in $csv_file"
fi
done < "$input_file"
这是输出的示例
192.168.1.2 found in network-data.csv
awk: fatal: `192.168.1.2' is not a legal variable name
192.168.1.18 found in network-data.csv
awk: fatal: `192.168.1.18' is not a legal variable name
192.168.1.33 not found in network-data.csv
192.168.1.44 not found in network-data.csv
192.168.1.51 found in network-data.csv
awk: fatal: `192.168.1.51' is not a legal variable name
答案1
我使用 AWK 而不是 Bash。
awk -f awkscript.awk ipaddresses.txt csvfile.csv
BEGIN {
FS = ","; # Assuming CSV fields are separated by commas
}
# Load the IP addresses from file1 into an array
NR == FNR {
ips[$0] = 1;
next;
}
# Now we're working with the CSV file
{
# The IP address is in the 16th field of the CSV
if ($16 in ips) {
print $1, $2; # Print columns 1 and 2
}
}