1

Consider a file.txt file with below values

one,two
three,four
five,six
six,seven
red,tree

Need a shell script command to perform below activity

  1. For loop in which the loop should be continuously executed with as many number of lines the file.txt has
  2. In each loop execution, the respective line should be considered a input for the execution.

For example, in first loop execution, "one" should be stored in a variable and "two" should be stored in another variable so that it will use the variable values in execution

Input1="one"
Input2="two"

Similary for second line execution, "three" should be stored in a variable and "four" should be stored in another variable like below

Input1="three"
Input2="four"
Michael Homer
  • 76,565

2 Answers2

4
while IFS=, read -r input1 input2; do
    # do stuff with "$input1" and "$input2"
done <file.txt

Setting IFS to a comma for the read command will make it split each input line on commas. The two fields of the line will be read into input1 and input2.

If there are more fields than two on any line, the "left over" data will be put into input2.

Depending on what you want to do with the data, this may or may not be a good idea at all. See Why is using a shell loop to process text considered bad practice?

You will notice that awk is particularly useful for parsing data like this, without the need for a loop:

$ awk -F, '{ printf("Line %d:\n\tField 1 = %s\n\tField 2 = %s\n", NR, $1, $2) }' file.txt
Line 1:
        Field 1 = one
        Field 2 = two
Line 2:
        Field 1 = three
        Field 2 = four
Line 3:
        Field 1 = five
        Field 2 = six
Line 4:
        Field 1 = six
        Field 2 = seven
Line 5:
        Field 1 = red
        Field 2 = tree
Kusalananda
  • 333,661
  • In order to avoid all additional input being lumped into input2 you can create a third var to collect it all: while IFS=, read -r input1 input2 garbage; do – jesse_b Oct 07 '17 at 22:25
3

It's unclear what you're asking. Why do you need the whole file in each iteration.

Do you need this?

while IFS=, read -r Input1 Input2; do
    # do something with the variables
    echo "1=$Input1  2=$Input2"
done < file.txt
glenn jackman
  • 85,964