M HYPE SPLASH
// news

Using multiple variables in a for loop

By Emily Wilson

I want to use two variables in a for loop like this (This is for example, I'm not going to execute seq like operations)

for i j `seq 1 2` ' echo $i $j;done

Expected output is

1

2

3 Answers

If i was to just be a number that incremented with each string, you could try a for loop and increment i with each iteration.

For example:

i=1; for j in ' ' do echo "$((i++)) $j"; done
3

Lets create variable to point to the file location

FILE="/home/user/myfile"

The file content:

To get the output of:

1
2 

It can be done by one of the following methods below:


Using counter variable:

i=1;
cat $FILE | while read line; do echo "$((i++)) $line";
done

Using cat -n (number all output lines)

cat -n $FILE | while read line; do echo "$line";
done

Using array:

array=( );
for i in "${!array[@]}"; do echo "$((i+1)) ${array[$i]}";
done

If your file already with line numbers, example:

1
2 

Loop and split every line to array:

cat $FILE | while read line; do col=( $line ); echo "${col[0]} ${col[1]}";
done

For more info:

Here are some alternative ways, two short and simple ones:

 printf "%s\n" | cat -n 

and

 for i in do echo $i; done | cat -n

which both output:

 1 2 

and the slightly more complex:

s=( )
for i in $(seq 1 ${#s[@]}); do echo $i ${s[i-1]}
done

that outputs:

1
2 

In that second suggestion, I'm using an array named s created with the line s=(xx yy)

The ${#s[@]} syntax is the number of elements in the array, here 2 and the ${s[i-1]} is element at offset i-1 from the beginning of the array, thus ${s[1-1]} is ${s[0]} and then is , etc.


2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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