1

I need to create a script to scan folders in a directory and take the name of each folder, make a .txt file, name it with the name of the folder and put inside that folder.

For example: A directory that has 3 folders in it named "1" "2" and "3" I want to create a .txt file in each folder named with the name of that folder so that folder 1 has "1.txt" in it folder 2 has "2.txt" in it etc..

I managed to do that with this script:

for i in $(ls -d */); do touch "$i $(basename $i).txt" ; done

The problem is I want to do the same thing but with folders that has spaces in their names. For example: If I have a folder named "Test Me" It will give an error saying something like this:

Me: no directory with that name

It will see only the word "Me" and treat it as a folder and not "Test Me" as a whole.

How can I do that ?

Update This is the solution, it is commented below by TAAPSogeking (Thanks again to him) for dir in *; do [ -d "$dir" ] && touch "$dir/$dir.txt"; done

ilkkachu
  • 138,973

2 Answers2

1

Assuming you just want the immediately directories and not all nested sub directories. The following assumes you are currently in the same directories and the directories you want to loop over

for dir in *; do 
    [ -d "$dir" ] && touch -- "$dir/$dir.txt"
done
  1. This will loop over every file in the current directory
  2. filter for directories (including symlinks to directories).
  3. And then create the requested file in the specified directory

Also you may be interested in shellcheck which point out common errors/bad practices (like the use of ls in this case)

0

With zsh, you could do:

touch -- *(/e['REPLY+=/$REPLY.txt'])

Where the / glob qualifier restricts the glob expansion to files of type directory (change to -/ if you also want to consider symlinks to directories), and the e qualifier evaluates the given code to modify the path (stored in $REPLY). Add the D (for Dot files) qualifier to also do it for hidden directories (. and .. not included in any case).