Home > Back-end >  Is there a way to use a for loop to create directories based on filenames?
Is there a way to use a for loop to create directories based on filenames?

Time:10-23

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.

CodePudding user response:

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.

  • Related