create a file in each subdirectory and write its path into it

I'm studying Linux and I've found an interesting exercise. Create a number of directories in ~ (abc, abc/def, abc/xyz, abc/def/ghi/123, abc/def/ghi/456), which is an easy task. After that create a file called 1.txt in abc and each of its subdirectories, writing the path of the files to them (for example ~/abc/def/1.txt should contain its path inside itself).

I used find /home/alex/abc -exec touch {}/1.txt \; which tried creating home/alex/DIRECTORY/1.txt/1.txt for each of the subdirectories, though, hopefully, creating the 1.txt files I need, but it's still incorrect behavior and therefore not good.

The bigger problem is writing file path to each of these 1.txt. I can use find /home/alex/abc -name 1.txt to locate each of them but I have no idea how to write each separate line to each separate file. I've been trying to do it with -exec and xargs but nothing worked at all.

So, how can I do it?


If you have already made the directories, then do:

find ~/abc -type d -exec sh -c 'echo "$1"/1.txt > "$1"/1.txt' _ {} \;

This runs sh -c 'echo "$1"/1.txt > "$1"/1.txt' for each directory (and only directories, because of -type d), with _ and the path to the directory as arguments. Then echo "$1"/1.txt > "$1"/1.txt outputs the path + 1.txt to a file named the same. This will also create the files as needed.