NewUsr_stat
NewUsr_stat

Reputation: 2573

split files in corresponding folders

I have a list of files, for example (pippo1.txt, pippo2.txt, pippo3.txt, ecc) in a master folder called "test".

I would like to create a number of folders equal to the number of files and with the same name. For example, if I have a file called pippo1.txt, I would like to create a folder called pippo1 and then I would like to copy the .txt files in folders called pippo1, pippo2, pippo3 respectively so that pippo1.txt will stay in folder pippo1, pippo2.txt will stay in folder pippo2 ecc.

I have 14469 files.txt to allocate in 14469 folders.

How can this be done?

Upvotes: 0

Views: 208

Answers (2)

Igor Chubin
Igor Chubin

Reputation: 64563

In Bourne shell:

for i in *.txt
do 
  dir=$(echo $i | sed 's/.txt$//')
  mkdir "$dir"
  cp "$i" "$dir"
done

In bash you can use ${} construction insted of sed:

for i in *.txt
do 
  dir=${i%.txt}
  mkdir "$dir"
  cp "$i" "$dir"
done

If you want to move the file and not copy it, just use mv instead of cp.

When you think that your list is too big for the command line (but it seems not to be too large in you case) you can use while...read instead of for:

find . -maxdepth 1 -name '*.txt' | while read i
do 
  dir=${i%.txt}
  mkdir "$dir"
  cp "$i" "$dir"
done

Upvotes: 1

Tim Pote
Tim Pote

Reputation: 28029

for file in *.txt; do
  newdir="${file%.txt}"
  mkdir -p "$newdir"
  mv "$file" "$newdir"
done

If you want to keep a copy of pippo1.txt in the "master directory", use cp instead of mv. E.g.:

cp "$file" "$newdir"

Upvotes: 0

Related Questions