0

I would like to seek help regarding the code of creating folders and moving files to it. I want to create folders, place the files ending with specific extension and only certain number of files in each folder. For example, I have 10 text files, create 5 folders, each folder having two files. (Files have names like 1.txt, 2.txt , .... , 10.txt. So 1.txt and 2.txt should be in folder 1, 3.txt and 4.txt in folder 2 and so on.

My code looks like this:

end=2
sta=1
for i in {1..5}
do
    mkdir "$i"
    for file in *.txt:
    do
        mv "{$sta..$end}.txt" "$i"
    done
    end=$((end+2))
    begin=$((begin+2))

done

It should be similar to it but I have an error,"mv: cannot stat '{1..10}.txt': No such file or directory".

I know it will be a simple change but couldn't figure it out. I have gone through the previous questions but couldn't sort my code.

Thanks!

soosa
  • 125
  • 11

3 Answers3

1

As pointed here,

bash does brace expansion before variable expansion, so you get weekly.{0..4}. Because the result is predictable and safe(Don't trust user input), you can use eval in your case:

$ WEEKS_TO_SAVE=4
$ eval "mkdir -p weekly.{0..$((WEEKS_TO_SAVE))}"

note:

eval is evil use eval carefully Here, $((..)) is used to force the variable to be evaluated as an integer expression.

So lets use eval in your case:

end=2
sta=1
for i in {1..5}
do
    mkdir -p "$i"
    for file in *.txt:
    do
        eval "mv {$((sta))..$((end))}.txt $i"
    done
    end=$((end+2))
    sta=$((sta+2))
done
Marcos Oliveira
  • 449
  • 4
  • 4
0

You can try the arithmetic substitution version of for as below :

((for i=1; i<=5; i++))

Explanation : brace expansion, {x..y} is performed before other expansions, so you cannot use that for variable length sequences.

EDIT AFTER MV ERROR WAS RESOLVED

#!/bin/bash

count=$(ls -lrt *.txt | wc -l)

for ((i=1;i<=$count/2;i++))
do
mkdir $i
a=$(find . -maxdepth 1 -name '*.txt' | cut -d'/' -f2 | sort -n|head -2)
mv $a $i
done
Nikhil Fadnis
  • 787
  • 5
  • 14
  • Thanks for the reply... I am able to create directories but cannot move the files into specified folders. – soosa May 24 '17 at 10:25
0

try it:

#!/bin/bash

sta=1
end=2
countFileInFolder=2
countFolders=5
filePath='/tmp/txt'
scriptDir=$(dirname $(readlink -f ${BASH_SOURCE}))

# create files for test
for (( k=1; k<=$(($countFolders*$countFileInFolder )); k++ )); do
  > "$filePath/$k.txt"
done

for (( i=1; i<=$countFolders; i++ )); do
    if [[ ! -d "$i" ]]; then mkdir "$i"; fi
  for (( n=$sta; n<=$end; n++ )); do
    if [[ ! -f "$i" ]]; then mv "$filePath/$n.txt" "$scriptDir/$i"; fi
  done
  sta=$(($sta+$countFileInFolder))
  end=$(($end+$countFileInFolder))
done
beliy
  • 445
  • 6
  • 13