質問

I'm new in shell script and I am trying to figure out a way to write a script that copies all the files in the current directory to a directory specified from a .txt file and if there are matching names, it adds the current date in the form of FileName_YYYYMMDDmmss to the name of the file being copied to prevent overwritting.

Can someone help me out?

I saw thinking something along the lines of

#!/bin/bash

source=$pwd          #I dont know wheter this actually makes sense I just want to
                     #say that my source directory is the one that I am in right now

destination=$1       #As I said I want to read the destination off of the .txt file

for i in $source     #I just pseudo coded this part because I didn't figure it out.   
do
   if(file name exists)
   then 
       copy by changing name
   else
       copy
   fi
done   

the problem is I have no idea how to check whether the name exist and copy and rename at the same time.

Thanks

役に立ちましたか?

解決

How about this? I am supposing that the target directory is in the file new_dir.txt.

    #!/bin/bash

    new_dir=$(cat new_dir.txt)
    now=$(date +"%Y%m%d%M%S")

    if [ ! -d $new_dir ]; then
            echo "$new_dir doesn't exist" >&2
            exit 1
    fi

    ls | while read ls_entry
    do
            if [ ! -f $ls_entry ]; then
                    continue
            fi  
            if [ -f $new_dir/$ls_entry ]; then
                    cp $ls_entry $new_dir/$ls_entry\_$now   
            else
                    cp $ls_entry $new_dir/$ls_entry
            fi  
    done 

他のヒント

I guess this what you are looking for :

#!/bin/bash

dir=$(cat a.txt)

for i in $(ls -l|grep -v "^[dt]"|awk '{print $9}')
do
    cp $i $dir/$i"_"$(date +%Y%m%d%H%M%S)
done

I assumed that a.txt contains only the name of the destination directory. If there are other entries, you should add some filter to the first statement(using grep or awk).

NB: I used full time stamp(YYYYMMDDHHmmss) instead of your YYYYMMDDmmss as it doesn't seem logical.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top