1

I have the following while loop:

while read LINE; do
  VALUE="`echo $LINE | cut -d"|" -f1`";
done

Notice the f1. This is the normal way I would use cut. This time around though, I need to increment f1 kinda like this:

while read LINE; do
  VALUE="`echo $LINE | cut -d"|" -f$COUNT`";
done

I cannot figure out the correct syntax. Can someone please help me? Thanks!

* UPDATE *

Here is my complete code (if this helps more)

declare -a FIELDS
local i
for i in "${!DBARRAY[@]}"; do
  local COUNT=1
  while read LINE; do
    VALUE="`echo $LINE | cut -d"|" -f$COUNT`";
    FIELDS[$COUNT]="$VALUE"

      Do stuff to each element of array here

    let COUNT=COUNT+1
  done < <(grep -v '#' databases/${DBARRAY[$i]})
done

* UPDATE *

Ok so I just realized my logic was flawed. The first for loop is to loop through all the databases. The while loop is to loop through every line in a single database. I needed a third loop to store each field to the array. See updated code below:

declare -a FIELDS
local i
local j
for i in "${!DBARRAY[@]}"; do
  local COUNT=1
  while read LINE; do
    for (( j=1; j<=24; j++ )); do
      VALUE="`echo $LINE | cut -d"|" -f"$j"`";
      FIELDS[$j]="$VALUE"
      echo "${FIELDS[$j]}"
    done
    let COUNT=COUNT+1
  done < <(grep -v '#' databases/${DBARRAY[$i]})
done

This code works woot!

0

2 Answers 2

1

You can use the read command itself to split the line:

for i in "${!DBARRAY[@]}"; do
    while IFS='|' read -ra FIELDS; do
        printf "%s\n" "${FIELDS[@]}"
    done < <(grep -v '#' databases/${DBARRAY[$i]})
done

http://www.gnu.org/software/bash/manual/bashref.html#index-read

Sign up to request clarification or add additional context in comments.

Comments

0

Ok so I just realized my logic was flawed. The first for loop is to loop through all the databases. The while loop is to loop through every line in a single database. I needed a third loop to store each field to the array. See updated code below:

declare -a FIELDS
local i
local j
for i in "${!DBARRAY[@]}"; do
  local COUNT=1
  while read LINE; do
    for (( j=1; j<=24; j++ )); do
      VALUE="`echo $LINE | cut -d"|" -f"$j"`";
      FIELDS[$j]="$VALUE"
      echo "${FIELDS[$j]}"
    done
    let COUNT=COUNT+1
  done < <(grep -v '#' databases/${DBARRAY[$i]})
done

This code works woot!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.