Feras Altwal
Feras Altwal

Reputation: 21

How to prevent file overwriting in bash script?

I am trying to automate a process which take a file type NIFTI, preprocess it, and places the new processed file in an output folder.

deepbrain-extractor -i <input-dir> -o <output-dir>

I wrote this bash script to automate this process for all files in a directory:

for file in path/*.nii
do
    deepbrain-extractor -i $file -o path/newfiles
done

The problem is every time the code runs, it overwrites the old files (since all automatically get the same name). Is there a way to prevent that?

Upvotes: 0

Views: 625

Answers (2)

Feras Altwal
Feras Altwal

Reputation: 21

Thanks for the suggestions and comments! seems like using this code gives me what I want.

deepbrain-extractor -i "$file" -o "${file%.nii}.out" 

Thanks a lot!!

Upvotes: 2

convex
convex

Reputation: 11

A common way to get a unique file name is to use the current date and time. You can combine this with the input file name to ensure that output files are never overwritten.

if [ ! -f "$FILE" ]; then
    echo "$FILE does not exist."
    for file in path/*.nii
    do
    deepbrain-extractor -i $file -o path/newfiles_${file##*/}_$(date +"%Y-%m-%d_%H-%M-%S")
    done
fi

so the output directory has a name like newfiles_input_2020-11-13_12-34-56

Also see How to create one output file for each file passed to a loop in bash?

Upvotes: 0

Related Questions