Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process every second file in bash?

I have a directory with a few dozens of files. I would like to do something with every second file from this directory. By now I only used find command but with this I process all files:

find ./dir/ -type f -exec cat {} \;
like image 204
klew Avatar asked Dec 29 '10 11:12

klew


2 Answers

for file in `find dir -type f | awk 'NR % 2 == 0'`; do
  echo $file
done

NR is the current row number. To get odd rows, use ... == 1.

like image 171
plundra Avatar answered Sep 30 '22 00:09

plundra


cnt=0; 
for file in $(find ./dir -type f); <-- if not too many matches
do 
  let cnt=cnt+1; 
  if [ $cnt -eq 2 ]; 
    then echo $file;               <-- do something
    cnt=0;                         <-- alternate file
  fi; 
done

or

second_file=$(find -type f | head -2 | tail -1);
like image 37
ajreal Avatar answered Sep 29 '22 22:09

ajreal