Script to List, Modify, replace filename for an upload?

Hello, here is my problem:

I have ma program in a first directory dir1:

ls path1/rep1/
file1.f90 file1.f90~ file1.o file2.f90 .... etc...

I have modified folder in an other directory:

ls path2/rep2/
file1_modified.f90 file2_modified.f90 .... etc...

All files from first directory are not all in the second (only the ones that are modified) but they have the same name plus "modified" at end.

I want to make a short script to:
1- save files of 1st directory from file1.f90 to file_old.f90 if the upload didn't work.

2- copy all files from 2nd directory to the first and change their name as needed.

Do you know how to do this and manipulate filename string and path to do that ?

thanks for your help :slight_smile:

What upload? Are the _modified files the ones arriving, being uploaded?

Sorry, I was not very clear :wall:

What I want is that:

step 1:
in path1/rep1/

cp file1.f90 file1_old.f90

but for all f90 files and i don't know how to easily manipulate filename string

step2:

cp /path2/rep2/file1_modified.f90 path1/rep1/file1.f90

and i want to do it for all file.f90 of the rep2 automatically.

so file1.f90 will be replace in the second step.

How should I modify the string filename ?

This script would do the job:

#!/bin/sh
for mod_file in path2/rep2/*_modified.f90
do
        base_name=$(basename ${mod_file});
        base_part=${base_name%_modified*};
        target_file=path1/rep1/${base_part}.f90;
        if [ -f $target_file ]
        then
                save_file=path1/rep1/${base_part}_old.f90;
                cp ${target_file} ${save_file}
        fi
        cp ${mod_file} ${target_file}
done

One detail - if you don't want to copy a modified file which does not exist in the path1/rep1 then move the last copy statetment inside the if - fi bracket right after the copy target to save old file statement.

If you are learning shell scripting pay attention to string manipulation (see how base_part of the file name is extracted) it comes handy quite often.

Hello,

I tried your solution but apprently, the test doesn't work well since no action that have to be done if the "if" test are done.

I tried to replace the test from

if [ -f $target_file]

to

if [test -f $target_file]

but it says

./upload.sh: 25: [test: not found

So, what should I do to test properly the existence of the file ?

thanks for your hellpull help!! :smiley: :wink:

Both [ and test are the same command.

if test -f "$target_file"

or:

if [ -f "$target_file" ]  ## spaces are required

THANKS ! it works perfectly now !

:smiley: :b:

But why thes space are so important ? :confused:

Do you think that fortune and for tune are the same thing?

No? Then why would you think that [-f and [ -f are the same?

It helps to remember that, on really really old systems, [ wasn't a language construct, there was actually a file like /bin/[