How do I create a directory for every file in a parent directory

17,294

Solution 1

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

Solution 2

Instead of loop you can use find

find ParentFolder/* -prune -type f -exec \
  sh -c 'mkdir -p "${0%.*}" && mv "$0" "${0%.*}"' {} \;
Share:
17,294

Related videos on Youtube

Gilles 'SO- stop being evil'
Author by

Gilles 'SO- stop being evil'

Updated on September 18, 2022

Comments

  • Gilles 'SO- stop being evil'
    Gilles 'SO- stop being evil' over 1 year

    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
    
  • T.m Chronos
    T.m Chronos over 4 years
    Could you further elaborate the "${0%.*}" ?
  • lauksas
    lauksas about 4 years
    This was actually very useful for me to organize my investments and it's redemptions in each folder, many thanks. every question answered saves me time to not having to create the solution myself :D
  • Christoph
    Christoph about 2 years
    One minor detail: for "./*.txt" ${x%.*} will output "./File1", "./File2" etc. with leading "./". Use "*.txt" instead "./*.txt" to just get "File1", "File2" without leading "./"