Consider a file.txt file with below values


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


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

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
  • 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 7 '17 at 22:25

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.