将文件从源文件夹递归复制到目标/*file_extension*(例如“txt”)文件夹

将文件从源文件夹递归复制到目标/*file_extension*(例如“txt”)文件夹

这是我的代码,rec_copy() 函数中的某些内容无法正常工作,扩展名文件夹是在目标文件夹中创建的,但文件不会复制到那里。

#!/bin/bash
if [ $# -ne 2 ]
then
        echo "Usage: $0 <source> <destination>"
        exit
fi

if [ ! -d $1 ]
then
        echo "Source folder does not exist"
        exit
fi

if [ -d $2 ]
then
        rm -r $2
        mkdir $2
else
        mkdir $2
fi

extension=`ls -l $1 | grep -v "^d" | awk '{ print $10; }' | sed 's/^.*\.//g'`
for f in $extension
do
        if [ ! -d $1/$f ]
        then
                mkdir $2/$f
        fi
done

rec_copy(){
folder=`ls $1`
for f in $folder
do
        dest=`echo "$f" | sed 's/.*\.//g'`
        if [ -f $1/$f ]
        then
                cp $1/$f $HOME/$2/$dest
        elif [ -d $1/$f ]
        then
                rec_copy $1/$f
        fi
done
}

rec_copy $1

答案1

这是答案,以防有人需要它:

#!/bin/bash

if [ $# -ne 2 ]
then
        echo "Usage: $0 <izvor> <destinacija>"
        exit
fi

if [ ! -d "$1" ]
then
        echo "Izvorniot folder ne postoi"
        exit
fi

if [ -d "$2" ]
then
        rm -r "$2"
        mkdir "$2"
else
        mkdir "$2"
fi

extension=`ls -l "$1" | grep -v "^d" | awk '{ print $10; }' | sed 's/^.*\.//g'`
for f in $extension
do
        if [ ! -d "$1/$f" ]
        then
                mkdir "$2/$f"
        fi
done

rec_copy(){
folder=`ls "$1"`
for f in $folder
do
        dest=`echo "$f" | sed 's/.*\.//g'`
        to=`cp "$1/$f" "$2/$dest"`

        if [ -f "$1/$f" ]
        then
                echo "$to"
        elif [ -d "$1/$f" ]
        then
                rec_copy "$1/$f" "$2"
        fi
done
}

rec_copy "./$1" "./$2"

相关内容