Home > Back-end >  How to loop through multiline array from a file and assign each line to multiple arguments?
How to loop through multiline array from a file and assign each line to multiple arguments?

Time:10-22

I have a text file like this;

192.168.1.1 apple orange
192.168.1.2 banana
192.168.1.3 kiwi melon cherry

I want to loop through this file line by line and assign items in each line to multiple arguments. So for instance, when I run it like this;

for loop from textile above;
    echo "Args: $1 $2 $3 $4"
done

It should give this output;

Args: 192.168.1.1 apple orange
Args: 192.168.1.2 banana
Args: 192.168.1.3 kiwi melon cherry

Also, as you can see each line may contain between 1 and 3 parameters after the IP which is fixed. So IP is always there and it's $1 and the rest can change between $2 and $4.

How can I do this? I was able to read the file by using mapfile but couldn't get the args from that.

CodePudding user response:

mapfile assigns the lines of its standard input to the entries of an indexed array, while you want to assign the fields of each line to an array. This is not the same. If your input file is as simple as what you show then something like the following could work:

$ while read -r -a args; do
  set -- "${args[@]}"
  echo "$# arguments: $@"
done < textfile.txt
3 arguments: 192.168.1.1 apple orange
2 arguments: 192.168.1.2 banana
4 arguments: 192.168.1.3 kiwi melon cherry

But if your inputs are more complex (e.g., with spaces in arguments), this will of course not work as you expect.

EDIT: changed set "${args[@]}" to set -- "${args[@]}" after seeing Paul's answer.

CodePudding user response:

Based solely on OP's desired output:

$ sed 's/^/Args: /' textfile.txt
Args: 192.168.1.1 apple orange
Args: 192.168.1.2 banana
Args: 192.168.1.3 kiwi melon cherry

Assuming OP's real requirement is to do something with the values (other than echo to stdout):

while read -r ip fruit1 fruit2 fruit3
do
    echo "Args: ${ip} ${fruit1} ${fruit2} ${fruit3}"   # yeah, extra spaces when fruit? is empty but visually not noticeable

    # or do other stuff ...
    
done < textfile.txt
  • Related