How to process every second file in bash?

后端 未结 4 1274
忘掉有多难
忘掉有多难 2021-02-15 23:55

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 thi

相关标签:
4条回答
  • 2021-02-16 00:04
    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);
    
    0 讨论(0)
  • 2021-02-16 00:13

    I had every file twice, and needed to delete every second file. Find just returned me random files, therefore I added a sort. It now looks like this:

    #!/bin/bash
    DIRNAME="<directoryNameContainingYourFiles>"
    for file in `find $DIRNAME -type f | sort | awk 'NR % 2 == 0'`; do
      echo "going to modify" $file
      #  ls -laFh $file           # show file details
      #  rm $file                 # delete file
      #  mv $file <newDirName>    # move file to <newDirName>
    done
    

    put this in a file called scriptName, run

    chmod +x scriptName
    

    and start it by calling

    ./scriptName
    
    0 讨论(0)
  • 2021-02-16 00:19

    If you want to run my_cmd on each of the alternate file, this may help

     find ./dir -type f | sort -n | sed -n '1~2!p'  | sed 's/^/mycmd  /' | sh
    

    I've copied the sed from How to remove every other line with sed?

    0 讨论(0)
  • 2021-02-16 00:22
    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.

    0 讨论(0)
提交回复
热议问题