I have a bash script with an ipaddress.txt input file, that I want to use against a csv file. I want find the IP and then display the values of Column A (for now). I may want to display two or three columns. The script im using finds the IP but is not printing the value in Column A. To note: if it helps with the answer, IP address location is the 16th Column or Column P of csv file.
#!/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"
Here's a sample of the output
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
awk -F, -v ip="$ip_address" '$16 == ip { print $1 }' "$csv_file"
however you really don't need a shell loop here at all, all the processing could be done by reading both files into awk