Bash – How to create a directory for every file in a parent directory

bashfilesshell-scripttcsh

I have parent folder and inside this folder I have 4 files

ParentFolder
      File1.txt
      File2.txt
      File3.txt
      File4.txt

I wanted to create subfolders inside the parent folder and carry the name of the files then move every file inside the folder that carry it is name like:

ParentFolder
    File1          
      File1.txt
    File2          
      File2.txt
    File3          
      File3.txt
    File4          
      File4.txt

How can I do that in batch or tsch script?
I tried this script:

#!/bin/bash
in=path_to_my_parentFolder
for i in $(cat ${in}/all.txt); do
cd ${in}/${i} 
ls > files.txt
for ii in $(cat files.txt); do
mkdir ${ii}
mv ${ii} ${in}/${i}/${ii} 
done     
done

Best Answer

You're overcomplicating this. I don't understand what you're trying to do with all.txt. To enumerate the files in a directory, don't call ls: that's more complex and doesn't work reliably anyway. Use a wildcard pattern.

To strip the extension (.txt) at the end of the file name, use the suffix stripping feature of variable substitution. Always put double quotes around variable substitutions.

cd ParentFolder
for x in ./*.txt; do
  mkdir "${x%.*}" && mv "$x" "${x%.*}"
done
Related Question