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
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);
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
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?
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
.