Home > Net >  For loop not reading it per line
For loop not reading it per line

Time:03-02

Trying to loop on a file that contains (see below) but it's not individually taking it per line per row.

7b.01.10  0  0.00   0.00   ....  .    0.00  ....  .
3c.00.2   0  0.00   0.00   ....  .    0.00  ....  .
7b.01.0   0  40.18  40.18  1.00  134  0.00  ....  .
3c.00.3   0  35.65  35.65  1.00  135  0.00  ....  .
7b.01.1   0  28.30  28.30  1.00  133  0.00  ....  .
3c.00.4   0  44.71  44.71  1.00  133  0.00  ....  .
7b.01.2   0  32.82  32.82  1.00  131  0.00  ....  .
3c.00.5   0  40.75  40.75  1.00  134  0.00  ....  .
7b.01.3   0  37.92  37.92  1.00  137  0.00  ....  .
3c.00.6   0  32.82  32.82  1.00  133  0.00  ....  .
7b.01.4   0  30.56  30.56  1.00  138  0.00  ....  .

what I want to process is the value in each of the lines. For example, the first line.

F1=7b.01.10
F2=0
F3=0.00
F4=0.00
F5=....
F6=.
F7=0.00
F8=....
F9=.

The reason is that I will be using each variable for another if statement within the loop. Ex: ans=F1*F4

for i in `cat file.txt`; do
        F1=`echo "${i}" | awk '{ print $1 }'`
        F2=`echo "${i}" | awk '{ print $2 }'`
        F3=`echo "${i}" | awk '{ print $3 }'`
        F4=`echo "${i}" | awk '{ print $4 }'`
        F5=`echo "${i}" | awk '{ print $5 }'`
        F6=`echo "${i}" | awk '{ print $6 }'`
        echo "$F1 $F2 $F3 $F4 $F5 $F6 "
done

any idea what am i missing?

CodePudding user response:

#!/bin/bash

input="data.txt"
while IFS= read -r line
do
        read -ra array <<< "$line"
        F1="${array[0]}"
        F2="${array[1]}"
        F3="${array[2]}"
        F4="${array[3]}"
        F5="${array[4]}"
        F6="${array[5]}"

        echo "$F1 $F2 $F3 $F4 $F5 $F6 "

done < "$input"

CodePudding user response:

This Shellcheck-clean code handles a common issue with text data files:

#! /bin/bash -p

inputfile='data.txt'
while read -r f1 f2 f3 f4 f5 f6 f7 f8 f9 || [[ -n $f1 ]]; do
    printf '%s\n' "$f1 $f2 $f3 $f4 $f5 $f6 $f7 $f8 $f9"
done < "$inputfile"

CodePudding user response:

You might want to use read

while read line; do
       echo $line
done < file.txt

This should print the file line by line. So, now, you get to do your magic with each line .

  • Related