LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Using "i" and "i+1" at the same time (https://www.linuxquestions.org/questions/linux-newbie-8/using-i-and-i-1-at-the-same-time-925409/)

kaveiros 01-24-2012 03:48 AM

Using "i" and "i+1" at the same time
 
Hi to all,

I have a list of files : file1, file2, ... file48, and I want to use each time 2 files. First file1 and file2, then file2 and file3, then file3 and file4 etc. In a for loop, is it possible to echo both "i" and "i+1" from my file list?


Thanks in advance.

catkin 01-24-2012 04:18 AM

Which language are you using?

lithos 01-24-2012 04:58 AM

Hi,

the logic you need is (this is in PHP):
PHP Code:

for ($i 1$i <= $numfiles$i++) {
// loop through i from 1 to $numfiles (total number of files)
    
echo $i;
//   do something with files
      
for ($n 0$n <= 1$n++) {
        echo 
"Current file number is: ".$i+$n;  // first loop gets i=1, n=0, meaning i+n=1
        // second loop gets i=1, n=1, meaning i+n=2 etc...
      
}  // end loop for n
}  // end loop for i 

I hope this helps you.

kabamaru 01-24-2012 08:00 AM

How about this?

Code:

#!/bin/bash

for ((i = 1; i <= 48; i += 2)); do
    echo "Do something with file$i and file$((i+1))"
done


David the H. 01-24-2012 08:55 AM

i=i+1, i++, and other variations thereof, when done in an arithmetic context, set the variable to the new value. Once executed, the previous value is lost.

To add another variation to the above suggestions, how about simply using a second variable?

Code:

nofiles=20
for (( i = 1; i <= nofiles; i++ )); do

        (( j = i + 1 ))
        echo "file$i file$j"

done

If the filenames are stored in an array first, it's also possible do something like this (assuming bash):

Code:

files=( * )
for i in "${!files[@]}"; do

        echo "${files[i]} ${files[i+1]}"

done

The [..] field in array expansion carries an arithmetic context, allowing such operations to be done inside them.

kaveiros 01-25-2012 03:34 AM

Thank you all for your answers.
Currently I solved this in a more "newbie" way. Maybe I should have added that I read my list of files from a text file.

Again,
many thanks!


All times are GMT -5. The time now is 05:08 AM.