1

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"
var2="high"
var3=124400
#repeat process for next line
codeforester
  • 39,467
  • 16
  • 112
  • 140
Jmercier13
  • 13
  • 7

1 Answers1

0

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?

Community
  • 1
  • 1
codeforester
  • 39,467
  • 16
  • 112
  • 140