Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am implementing as below code using for loop but wrong output coming after running the script.

for i in `awk -F"|" '{print $1}' $INPUTFILE`, j in `awk -F"|" '{print $2}' $INPUTFILE`
do
echo $i:$j
done  

Please help me to use multiple variables in single for loop in shell script.

share|improve this question

Maybe you actually want:

while IFS='|' read -r i j rest <&3; do
  {
    printf '%s\n' "something with $i and $j"
  } 3<&-
done 3< "$INPUTFILE"

But using a shell loop to process text is often the wrong way to go.

Here, it sounds like you just need:

awk -F '|' '{print $1 ":" $2}' < "$INPUTFILE"

Now as an answer to the question in the title, for a shell with for loops taking more than one variables, you've got zsh (you seem to already be using zsh syntax by not quoting your variables or not disabling globbing when splitting command substitution):

$ for i j in {1..6}; do echo $i:$j; done
1:2
3:4
5:6

Or the shorter form:

for i j ({1..6} echo $i:$j

The equivalent with POSIX shells:

set -- 1 2 3 4 5 6
## or:
# IFS='
# ' # split on newline
# set -f # disable globbing
# set -- $(awk ...) # split the output of awk or other command
while [ "$#" -gt 0 ]; do
  echo "$1:$2"
  shift 2
done
share|improve this answer

You'll need multiple loops if you want to iterate over more than one variable, like for i in 1 2 3; do for j in a b c; do ...; done; done. when the list of things to iterate over is the output of a another command, you'll need to wrap that other command in $().

share|improve this answer
    
I am not sure OP want a cross product, more likely OP want i,j from first line of $INPUTFILE, then i,j from second line and so on. – Archemar Apr 28 at 15:42
    
I opted for not trying to parse the awk parts of the question, but after re-reading it, I think you're right an that Stephane's answer is right on. – Henrik Apr 28 at 17:10

bash allows for loops with more than one variable, but only in C like syntax:

for ((i=0,j=10;i<=j;i++,j--))
do
   echo "i=$i"
   echo "j=$j"
done
share|improve this answer
    
how are i and j read from $INPUTFILE ? – Archemar Apr 28 at 15:43
    
@Archemar They're not. The question, I believe, is wrong. Using for loops on awk is usually wrong as you can usually accomplish whatever you wanted in pure awk, and see Stéphane Chazelas's answer. I just answered the question in the title. – Dani_l Apr 28 at 16:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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