Unix/Linux: How to get the top-level directory (only) from a file path

I worked with ChatGPT today to solve the following Unix/Linux problem:

If I have a file that has one or more filename paths like this:

/home/alvin/a/b/c/d/e/foo.txt

How do I get only the "/home" portion of that string, i.e., only the top-level directory name from those canonical filename paths?

Assuming that all the filenames are in a file named file_list, this is the solution:

for file in `cat file_list`
do
    dir_name=$(dirname "$file")
    echo "$dir_name"
done | cut -d'/' -f 2 | sort -u

In my case, that printed out a list similar to the following:

akka-2.3
clojure
commons-lang
deeplearning4j

Note that if your filenames start with a leading / character, you’ll probably need to change that 2 to a 1.