3

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

example:

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

all my .jpg files are in

/root/Desktop/My_pictures

so it should look like this:

example picture "cat.jpg"

/root/Desktop/My_pictures/cat/pictures/cat.jpg

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

Best Regards and Thank You

2
  • 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, 2014 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, 2014 at 23:00

2 Answers 2

6

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

#!/bin/bash

for full_filename in *jpg; do
  extension="${full_filename##*.}"
  filename="${full_filename%.*}"
  mkdir -p "$filename/picture"
  mv "$full_filename" "$filename/picture"
done

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

3
  • Could you add an explanation of the string manipulation tools you are using?
    – terdon
    Mar 26, 2014 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. Mar 27, 2014 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, 2014 at 6:29
3

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
do
    ## 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"
done

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

~/movefiles.sh

Not the answer you're looking for? Browse other questions tagged .