Search code examples
linuxfor-loopmkdir

Is there a way to use a for loop to create directories based on filenames?


I want to create directories based on names of files I already have. For example, let's say I have:

red.txt green.txt blue.txt purple.txt orange.txt

Would there be a way to create directories called:

red/ green/ blue/ purple/ orange/ ?

I tried doing:

for f in *.txt; do mkdir {$f}; done

for f in *.txt; do mkdir {$f}.txt; done

for f in *.txt; do mkdir "$f/"; done

etc etc, variations thereof. I can't figure out what I'm doing wrong.


Solution

  • Here's a bash-only way of going about it ...

    for f in *txt; do mkdir ${f%.*}; done
    

    We employ bash's shell parameter expansion here, in case you're curious.