Rename files with its pathname

Hi,

I have a few csv files within the directory structure as shown below

/tmp/user/Proj/V1/data/Common1/Zip1/123.csv
/tmp/user/Proj/V1/data/Common2/Zip2/3453.csv
/tmp/user/Proj/V1/data/Common2/Zip2/1234.csv
and so on...



I need to get these csv files and move to another dir with the filename Common1_Zip1_123.csv,Common2_Zip2_3453.csv etc..I have written the following code but the filenames are having the whole path..Pl. correct on my code..

#!/bin/bash

SourceDir="/tmp/user/Proj/V1/data/
DestDir="/tmp/user/Proj/V1/data/FinalData"

for file in $(find $SourceDir -type f -name *.csv); do
        shortname=${file##*/$SourceDir/}
        newname="$DestDir/${shortname//\//_}"
        if [ -f $newname ]; then
                echo "$newname already exists."
        else
                cp $file $newname
        fi
done

 

The output i am getting is:

_tmp_user_Proj_V1_data_COMMON1_ZIP1_123.csv

Hi

cd /tmp/user/Proj/V1/data/
find * -not -path "FinalData/*" -name "*.csv" |
    while read d; do
        echo cp $d FinalData/${d//\//_};
    done

Thank you. But it seems the files are not getting copied. Any other solution pl.

remove echo

echo cp $d FinalData/${d//\//_}  #testing
cp $d FinalData/${d//\//_}

and insert test if need

if ! [ -e FinalData/${d//\//_} ]; then
    cp $d FinalData/${d//\//_}
fi
2 Likes

Thank you. It helped.

out of interest a couple of small issues were causing your original attempt to fail:

#!/bin/bash

SourceDir="/tmp/user/Proj/V1/data/"
DestDir="/tmp/user/Proj/V1/data/FinalData"

for file in $(find $SourceDir -not -path "${DestDir}/*" -type f -name *.csv); do
        shortname=${file#$SourceDir}
        newname="$DestDir/${shortname//\//_}"
        if [ -f $newname ]; then
                echo "$newname already exists."
        else
                cp $file $newname
        fi
done
2 Likes