LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   bash for loop: passing 2 arguments to a prog (https://www.linuxquestions.org/questions/linux-newbie-8/bash-for-loop-passing-2-arguments-to-a-prog-4175577667/)

beca123456 04-17-2016 12:49 PM

bash for loop: passing 2 arguments to a prog
 
Hi,

in '$HOME/Data/' directory I have a list a input files:
Code:

file1_X.tab
file1_Y.tab
file2_X.tab
file2_Y.tab

The program I am using needs two inputs from the same file number (below an example for 'file1'):
Code:

my_program \
    -I:X file1_X.tab \
    -I:Y file1_Y.tab \
    -O file1_output.tab

I am trying to use a bash 'for loop' to pass a group of file# to the program but I am kind of stuck.
I started something like the following but the problem is to pass 2 files by calling my_program once:
Code:

for A in *.tab
do

B=`basename ${A} _*.tab`

my_program \
    -I:X ${B}_X.tab
    -I:Y ${B}_Y.tab
    -O ${B}_output.tab

done


mralk3 04-17-2016 08:26 PM

I think the simplest form is to make an array of the files in their directory using the ls command.

Code:

[~]$ a=`ls /tmp`; echo $a
Just change the path to the directory.

EDIT: You would need to add a few more lines to grab the specific files you need each run. This is just meant to get you started.

grail 04-17-2016 10:54 PM

Whilst mralk3 suggestion to create an array is a good idea, the command supplied does not do this. To be an array the command substitution needs to be inside round brackets, like so:
Code:

a=($(ls /tmp))
I am also not a fan of using ls, so would probably change the above to a glob:
Code:

a=( *.tab )
The negatives for both of these is that they will also include directories if there are any so you would need to test for them.

The benefit of the glob over the command substitution is that the glob will not split on white space.

Your loop would also then change to the more traditional for loop:
Code:

for (( i = 0; i < ${#a[*]}; i+=2 ))

MadeInGermany 04-18-2016 10:19 AM

The traditional way saves some memory and maybe some CPU cycles
Code:

cnt=0; for file in *.tab
do
  if [ $((cnt+=1)) -eq 2 ]
  then
    echo "$file and $pfile"
    cnt=0
  else
    pfile=$file
  fi
done



All times are GMT -5. The time now is 09:31 AM.