Using multiple variables in a for loop
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;doneExpected 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";
doneUsing cat -n (number all output lines)
cat -n $FILE | while read line; do echo "$line";
doneUsing array:
array=( );
for i in "${!array[@]}"; do echo "$((i+1)) ${array[$i]}";
doneIf 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]}";
doneFor 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 -nwhich both output:
1 2 and the slightly more complex:
s=( )
for i in $(seq 1 ${#s[@]}); do echo $i ${s[i-1]}
donethat 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