Search code examples
bashshellsh

Loop through directory with filenames with numbers in bash script


I have to perform a loop through a directory that contains files with the following scheme:

P1_1.fq.gz,  P1_2.fq.gz
P2_1.fq.gz,  P2_2.fq.gz
...
P10_1.fq.gz,  P10_2.fq.gz

The purpose is take "one line" at a time. For example, in one iteration I must take the first two file and operate on them. Then, take the others two and so on. How can I loop considering the numbers ? I think It will be something like this:

for i in {1..10}; do echo P$i_1.fq.gz; done

I have some problems on how can I take couples and not one file, and with the syntax regarding the letters after the $i variable, since I am not so expert with bash scripts.

What can I try next?


Solution

  • The _1 will be part of your variable this way. The solution is to explicitly tell bash what the variable is:

    for i in {1..10}; do
        echo '------------------'
        echo P${i}_1.fq.gz
        echo P${i}_2.fq.gz
    done