Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

Hello I need to create folder based on a filename and in this folder create another one and then move file to this second folder


create folder cat
create folder picture
move cat.jpg to picture 

all my .jpg files are in


so it should look like this:

example picture "cat.jpg"


Sorry if I'm not precise but English is not my native language.

Best Regards and Thank You

share|improve this question
Just some pointers: mkdir is used to create folders. cp is used to copy files. mv is used to move and/or rename files. Type man followed by the command you want to see the manual page of that command. Oh, and it's best to prepare your homework on your own :-) –  hmayag Mar 26 at 22:08
Please please please, don't log in to your computer as root. It is needlesly dangerous and especially when being a novice writing scripts, you might make a mistake and delete all your files. –  terdon Mar 26 at 23:00

2 Answers 2

You can also remove the ls *.jpg and simply use shell globbing:


for full_filename in *jpg; do
  mkdir -p "$filename/picture"
  mv "$full_filename" "$filename/picture"

Please create and run this script inside /root/Desktop/My_pictures.

share|improve this answer
Could you add an explanation of the string manipulation tools you are using? –  terdon Mar 26 at 22:58
@terdon Interesting. I did not know that "in *jpg" would handle filenames separated by space. Thanks! The construction "while read i; ... ; < <(cat file.txt)" is useful for taking line by line. If you do "for i in $(cat file.txt)" you would get word by word. –  Tinti Mar 27 at 15:54
Which is why you never do for i in $(cat file.txt), indeed. However, you don't do while read i; ...; < <(cat file) either, that is a classic useless use of cat and needlessly complex. Instead, do while read i; do command $i; done < file. –  terdon Mar 28 at 6:29

A similar approach:

#!/usr/bin/env bash

## iterate through each file whose name ends in 'jpg'
## saving it as $file. ~ is your $HOME directory
for file in ~/Desktop/My_pictures/*jpg
    ## basename will remove the path (~/Desktop/My_pictures) and also
    ## remove the extension you give as a second argument    
    name="$(basename "$file" .jpg)"

    ## create the directory, the -p means it will create 
    ## the parent directories if needed and it won't complain
    ## if the directory exists.
    mkdir -p ~/Desktop/My_pictures/"$name"

    ## copy the file to the new directory
    mv "$file" "~/Desktop/My_pictures/$name"

Save the script above as, for example, ~/movefiles.sh, make it executable with chmod +x movefiles.sh and run it:

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.