4

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

3 Answers 3

9

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 'www.google.com' 'www.yahoo.com'; do echo "$((i++)) $j"; done
3
  • why did you, use double braces in $((i++)). I think one braces is enought for this. Please correct me , If i said wrong.
    – SuperKrish
    Nov 5, 2016 at 8:32
  • 1
    @SuperKrish $(( . . .)) is arithmetic expansion, which is what makes i++ work. With single braces that's $(. . .) command substitution , so i++ 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 Nov 5, 2016 at 10:30
  • Great! @jake My doubt is clear
    – SuperKrish
    Nov 5, 2016 at 10:47
4

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:

3

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.


2
  • I dont know what is means ${#s[@]} `${s[i-1]}1. Here s is the variable loaded with some values.Can you clear my doubt?
    – SuperKrish
    Nov 5, 2016 at 14:15
  • Answer edited with explanations added.
    – jlliagre
    Nov 5, 2016 at 15:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .