I had this interesting question the other day. Someone had a file with two columns of data in it. They wanted to assign each column to a different variable and then take action using those two variables. Here's the example I wrote for them:
IFS=$'\n';
for LINE in $(cat data_file); do
VARA=$(echo ${LINE} | awk '{ print $1}')
VARB=$(echo ${LINE} | awk '{ print $2 }')
echo "VARA is ${VARA}"
echo "VARB is ${VARB}"
done
The key here is to set the internal field separator (${IFS}
) to $'\n'
so that
the for
loop iterates on lines rather than words. Then it's simply a matter of
splitting the column into individual variables. In this case, I chose to use awk
since it's a simple procedure and speed is not really an issue. Long-term, I would
probably re-write this using arrays.