Jmercier13 Jmercier13 - 4 years ago 113
Bash Question

Iterating through a result set in shell

So I've searched quite a bit for this and I'm pretty new to Shell,
I want to iterate over Resultset rows in SHELL script and for each row I want to execute some code using each column of the current row.
Lets assume the resultset look like this.

Query Priority Size
this is a sentence to execute high 124400
this is another example low 15000000

So how do I manage to iterate over this Resultset and storing each column into his own variable? Here is an exemple for the first line:

var1="this is a sentence to execute"
#repeat process for next line

Answer Source

Here is what you could do:

  • Extract your data into a delimited file (say, csv), if possible, avoid having headers. If you do have headers, make sure to exclude them while reading.
  • Read data from the file into an array or a set of variables

like so:

# using an array - works great if we have a variable number of columns
while IFS=, read -r -a row; do
  # ${row[0]} => column1, ${row[1]} => column2 and so on
  # process data
done < input.dat

# using variables - works great if we have a fixed set of variables
while IFS=, read -r column1 column2 column3; do
  # process data
done < input.dat

See also: How do I split a string on a delimiter in Bash?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download