Re: How to find directories that only contain a certain type of files (e.g., .txt)?

James Youngman <[email protected]>
Newsgroups gmane.comp.gnu.findutils.bugs
Message-ID <CAGwX765PH=p-rQTv6SJqt=dyeomvAJz0v2U4bSgtrmRz+s9cBA@mail.gmail.com>
Sometimes the thing you need to do isn't a precise fit for the tools
(in this case, find) you have, and the Bourne shell is not quite
powerful enough to directly express the algorithm you have in mind, so
it can be better to fall back on a scripting language, perhaps
something like this:

#!/usr/bin/python3

import os
import os.path
import pathlib
import sys

from typing import Optional, Sequence


def find_only(extension: str, start_points: Sequence[str]) -> int:
    for start in start_points:
        for dirname, _subdirs, files in os.walk(start):
            accept: Optional[bool] = None
            for file in files:
                path = pathlib.Path(os.path.join(dirname, file))
                if path.suffix == extension:
                    if accept is None:
                        accept = True
                else:
                    accept = False
                    break
            if accept:
                print(dirname)
    return 0


def main(args: Sequence[str]) -> int:
    if len(args) < 2:
        program = args[0] if args[0] else 'findonly'
        print(f"usage: {program} extension [start_point...]", file=sys.stderr)
        return 1
    extension = args[1]
    if not extension.startswith('.'):
        print("extension must start with a dot", file=sys.stderr)
        return 1
    return find_only(extension, args[2:])


if __name__ == '__main__':
    sys.exit(main(sys.argv))
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.