LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Shell script help! (https://www.linuxquestions.org/questions/linux-newbie-8/shell-script-help-4175548078/)

highland 07-15-2015 01:00 PM

Shell script help!
 
hi all, I am currently trying to create a simple script and having difficulty. The scripts job is to copy all files from a folder in my USB drive into a folder on my Linux virtual machine. Also if the folder in Linux is called "FLD" i'd like the files to be renamed FLD1, FLD2, FLD3 etc etc. Any help would be greatly appreciated. Very new to Linux and need this to work before I can get started on what i'd like to do.

Thanks!

igadoter 07-15-2015 04:03 PM

At first copy the files and next, after that go to directory where files were copied and rename all the files. Renaming "on the fly", I think is not best idea. .

berndbausch 07-15-2015 06:05 PM

Quote:

Originally Posted by highland (Post 5391879)
hi all, I am currently trying to create a simple script and having difficulty. The scripts job is to copy all files from a folder in my USB drive into a folder on my Linux virtual machine. Also if the folder in Linux is called "FLD" i'd like the files to be renamed FLD1, FLD2, FLD3 etc etc. Any help would be greatly appreciated. Very new to Linux and need this to work before I can get started on what i'd like to do.

Thanks!

Code:

TARGET=whatevertargetfolderyouneed
i=1
for file in *
do
    cp $file $TARGET/$TARGET$i
    i=$((i+1))
done

I didn't test it, please try it out.

The for loop iterates over all files in the current directory. Each file is copied to the target folder, to a file named after the target folder plus a number.
The number is then incremented. $(( ...)) is the arithmetic substitution syntax of the bash shell; if you need other shells to interpret this, you may need a different way of incrementing.
If your files can start with a dot, the head of the for loop must be altered.

igadoter 07-15-2015 07:05 PM

You may also have a look at this
http://www.linuxquestions.org/questi...ly-4175545992/
paticularly useful can be "rename" small Perl script (assuming you have Perl installed).

highland 07-18-2015 08:36 AM

Thanks for your reply guys! Unfortunately the above script didnt work, any ideas why? When i done the exec in console, the console disappeared and nothing happens to my target folders. My directories are called fdp and fdp2 which are located in my root directory:

TARGET=~/fdp
i=1
for file in *
do

cp $file $fdp/$fdp2$i
i=$((i+1))
done

is there a mistake in the algorithm somewhere? I really appreciate the help guys.

berndbausch 07-18-2015 09:05 AM

Quote:

Originally Posted by highland (Post 5393116)
Thanks for your reply guys! Unfortunately the above script didnt work, any ideas why? When i done the exec in console, the console disappeared and nothing happens to my target folders. My directories are called fdp and fdp2 which are located in my root directory:

TARGET=~/fdp
i=1
for file in *
do

cp $file $fdp/$fdp2$i
i=$((i+1))
done

is there a mistake in the algorithm somewhere? I really appreciate the help guys.

Why exec? Just run the script without exec.

"exec" will essentially replace your interactive shell with the program. When the program is done, the window naturally closes.

normanlinux 07-18-2015 10:05 AM

Shell script tips
 
A couple of tips when creating shell scripts:
Replace the command (i.e. cp above) with echo and run the script to see what it would do.
set -x on your new scripts to watch what they actually do
Play around to build up your confidence
Last, but most important of all Enjoy yourself learning the power of the command line and shell scripts
When you get stuck, ask here

highland 07-18-2015 12:41 PM

Still no luck getting the script to run :(. I'd like to try getting it done by first running a script to copy all contents from one directory onto the other, and this should be achieved by using
$script ~/FDP ~/FDP2

and then a second script which runs automatically which will rename all files within the directory according to the directory name.

Sorry for being such a noob!

normanlinux 07-18-2015 02:06 PM

Try this:
#!/bin/bash
if [ "$#" -ne 2 ] || ! [ -d "$1" ] || ! [ -d "$2" ]; then
echo "Usage: $0 fromDirectory toDirectory"
exit -1
fi
num=1;
for original in $1/*; do
extension=${original##*/}
ext=${extension##*.}
echo copying from "$original" to "$2/$2$num.$ext"
#cp "$original" "$2/$2$num.$ext"
(( num = $num + 1 ))
done
exit 0

Sorry, posts lose all indentation :-(

When you're happy, uncomment the cp line

highland 07-18-2015 02:21 PM

thanks norman, looks like were getting somewhere! however now i am getting error: CP: cannot create regular file /root/fdp2//root/fdp21.filefile : no such file or directory. To load the script i entered " script ~/fdp ~/fdp2

It does however say copying from /root/fdp/term (term being one of the files inside that directory) yet it doesnt actually copy it over. strange!

michaelk 07-18-2015 03:43 PM

normanlinux,
If you wrap your program in code tags i.e. your indentation will not be lost.

What you are seeing is just "echo copying from "$original" to "$2/$2$num.$ext"" and not an actual status message from the cp command. There are a few problems with the syntax of the cp command as posted which is why you see the error message. A few more steps are required to parse the destination directory and strip out the fdp2 from /root/fdp2.

normanlinux and berndbausch appear to be willing to write the script for you but you should learn it so you know how it works...

http://www.cyberciti.biz/open-source...for-beginners/

normanlinux 07-18-2015 04:10 PM

Michaelk: Thanks, unfortunately I used the quick reply :-(

Highland: Sorry, I didn't allow for the longer paths :-( You should look up the syntax for pattern operators then you can fix it.

I had to look this up myself as I use zsh which has a simpler (better?) way to do this

Aia 07-19-2015 02:46 AM

Code:

#!/bin/bash
#
# Author: Aia
# Date: 7/19/2015
# transfer.sh
# Educational example
# http://www.linuxquestions.org/questions/linux-newbie-8/shell-script-help-4175548078/
#
# This script will try to copy all the files found in a given source directory
# to a destination directory renaming the file according to the destination
# and a sequential prefix number. If the directory target is does not exist, it will
# be created.
# NO WARRANTY OF USABILITY IS IMPLIED



usage() {
    printf "${1}\n"
    printf "Usage: ${2} source_dir destination_dir\n"
    exit 1
}

# check that source was given
SOURCE_DIR_PATH="${1}"
if [[ -z "$SOURCE_DIR_PATH" ]]; then
    usage "Missing source directory" ${0}
fi

# check that source is valid
if [[ ! -d "$SOURCE_DIR_PATH" ]]; then
    usage "The source directory does not exist or is not a valid path" ${0}
fi

# check that destination was given
DESTINATION_DIR_PATH="${2}"
if [[ -z "$DESTINATION_DIR_PATH" ]]; then
    usage "Missing destination directory" ${0}
fi

# creates directory tree if it does not exist
mkdir -p "$DESTINATION_DIR_PATH"

# remove trailing / if exists
DESTINATION_DIR_PATH="${DESTINATION_DIR_PATH%/}"
SOURCE_DIR_PATH="${SOURCE_DIR_PATH%/}" # remove trailing / if exists

# check that the source is not the same that destination
if [[ $SOURCE_DIR_PATH == $DESTINATION_DIR_PATH ]]; then
    usage "source and destination cannot be the same" ${0}
fi

# get just the name of the directory
DST_DIR_NAME="${DESTINATION_DIR_PATH##*/}"

# to append to file name
suffix_id=1

# walk through the source directory
list=( "${SOURCE_DIR_PATH}"/* )
for ((i=0; i<${#list[@]}; i++)) do
    # only files will be copied
    if [[ -f ${list[i]} ]]; then
        target=${DESTINATION_DIR_PATH}/${DST_DIR_NAME}${suffix_id}
        if [[ -f "$target" ]]; then
            printf "Error: target file exist. Aborting!\n" >&2
            exit 1
        fi
        # comment this once if the result is what you want
        echo "coping ${list[i]} $target"
        # -v will output update to the screen
        #cp -v "${list[i]}" "$DESTINATION_DIR_PATH/$DST_DIR_NAME$suffix_id"
        suffix_id=$((suffix_id + 1))
    fi
done

Save as transfer.sh
Code:

chmod +x transfer.sh
USAGE: transfer.sh source_directory destination_directory

unSpawn 07-19-2015 04:49 AM

*One should rather use readline and 'while' loops to be safe: http://mywiki.wooledge.org/BashPitfalls.

highland 07-21-2015 11:41 AM

Thank you so much for all your help guys, learning so much in very little time.

Quick question, say my directory is called test, and I want the .jpg files in there to be renamed test1.jpg, test2.jpg etc, is there a quick way to do it? Rather than having a variable script that changes it accordingly, just a simple few lines of code?

Thanks!


All times are GMT -5. The time now is 12:32 PM.