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` 'www.google.com www.yahoo.com';do echo $i $j;done
Expected output is
1 www.google.com
2 www.yahoo.com
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` 'www.google.com www.yahoo.com';do echo $i $j;done
Expected output is
1 www.google.com
2 www.yahoo.com
Lets create variable to point to the file location
FILE="/home/user/myfile"
The file content:
www.google.com
www.yahoo.com
To get the output of:
1 www.google.com
2 www.yahoo.com
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=(www.google.com www.yahoo.com);
for i in "${!array[@]}"; do
echo "$((i+1)) ${array[$i]}";
done
If your file already with line numbers, example:
1 www.google.com
2 www.yahoo.com
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" www.google.com www.yahoo.com | cat -n
and
for i in www.google.com www.yahoo.com; do echo $i; done | cat -n
which both output:
1 www.google.com
2 www.yahoo.com
and the slightly more complex:
s=(www.google.com www.yahoo.com)
for i in $(seq 1 ${#s[@]}); do
echo $i ${s[i-1]}
done
that outputs:
1 www.google.com
2 www.yahoo.com
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 www.google.com
, etc.
${#s[@]}
`${s[i-1]}1. Here s is the variable loaded with some values.Can you clear my doubt?
– SuperKrish
Nov 05 '16 at 14:15
$((i++))
. I think one braces is enought for this. Please correct me , If i said wrong. – SuperKrish Nov 05 '16 at 08:32$(( . . .))
is arithmetic expansion, which is what makesi++
work. With single braces that's$(. . .)
command substitution , soi++
won't work there. If you were trying to catch output of another program, say$( df )
for example, you could use single braces. If you need calculation, then you use$(( . . . ))
structure – Sergiy Kolodyazhnyy Nov 05 '16 at 10:30