Home > Software engineering >  Bash loop trough files in directory manually
Bash loop trough files in directory manually

Time:01-26

I have N files in my directory, I want to be able to loop through them with batches, for example for 2/3/4 files I want to execute one command. I saw something like this, but can't find it, unfortunately. I will try to explain what I want using pseudo code, for example:

i=0
while i<N:
  a=getFile(i)
  b=getFile(i 1)
  dosomething a
  dosomething b
  i =2

Is there any way to do it in Bash? Right now I'm using regexp, but it gets one file at a time (I'm using *.ext because all files have one extension, so you can just loop through all files in the directory in your answer, if it's easier):

for j in *.ext; do   
 ...
done

CodePudding user response:

This would be the same with most programming languages: loop and store items somewhere until you have enough of them:

declare -i count=0
declare -a files=()
for f in *.ext; do
  files[count]="$f"
  (( count  = 1 ))
  if (( count == 2 )); then
    dosomething "${files[0]}"
    dosomething "${files[1]}"
    count=0
  fi
done

If you want to process your files in batches of more than 2 at a time we can also design something a bit more generic (adapt the value of batch):

declare -i batch=3
declare -i count=0
declare -a files=()
for f in *.ext; do
  files[count]="$f"
  (( count  = 1 ))
  if (( count == batch )); then
    for (( i=0; i<batch; i   )); do
      dosomething "${files[i]}"
    done
    count=0
  fi
done

CodePudding user response:

You can collect your arguments into an array, and then slice that any way you like.

array=( *.ext )
for ((i=0; i<=${#array[@]}; i =2)); do
    dosomething "${array[i]}" "${array[i 1]}"
done
  •  Tags:  
  • Related