I need to be able to search a flat file (comma-separated values) for a specific value and then return the following 2 fields into variables. Here's a sample flat file:
I already have BASH code that extracts the computer's serial number and stores it to SERIALNUM. I want to search the file for that SERIALNUM and return the following 2 fields in ACCT and IPADD. Suggestions?
i would suggest to first read in the whole file in three array, one for the serial, one for the user and one for the ipadd.
declare -a SERIAL ACCT IPADD
let count=0
while IFS=, read a b c
do
SERIAL[$count]=$a; ACCT[$count]=$b; IPADD[$count]=$c; ((count++))
done < file
This sets the internal field separator to "," and reads the three comma separate fields into the three variables which are pushed into the declared arrays.
Now you can search this array like this:
let i=0
while [[ $i -lt ${#SERIAL[@]} ]]
do
[[ ${SERIAL[${i}]} = W120* ]] && printf "%s %s\n" ${ACCT[${i}]} ${IPADD[${i}]}
((i++))
done
This loops trough the array. ${#SERIAL[@]} gives you the number of entries of an array. If a certain SERIAL is found, the corresponding data are output.
Great (and thanks), this got me 99% there. Here's a snippet of what I have, using your idea:
#!/bin/bash
USERLIST="/Users/johndoe/.bin/xBackup_users"
SRCHFOR="W8735UL8Z5V"
#
USERNAME=`awk -F "," '/W8735UL8Z5V/{print $2}' $USERLIST`
PASSWORD=`awk -F "," '/W8735UL8Z5V/{print $3}' $USERLIST`
RSYNCIP=`awk -F "," '/W8735UL8Z5V/{print $4}' $USERLIST`
#
clear
echo
echo Your account name is $USERNAME
echo Your password is $PASSWORD
echo Your IP address is $RSYNCIP
echo
exit
To finish this, I'd rather use the variable SRCHFOR in the awk command and I've tried it several ways, but aren't sure how to get it to work. (I already separate code that extracts the serial number from the machine.)
You need to specify a variable for use in awk, like done above. The -v says to set a variable, and the one assigned is pat, and it is equal to $SERIALNUM. You would need to do the same for your SRCHFOR variable. Then, you could use pat (or any other variable name you assign) within awk to do your matching.