Unix Bash-将文件从源文件夹递归复制到destination / * file_extension *(例如“ txt”)文件夹

时间:2018-08-29 15:03:53

标签: bash shell unix recursion

这是我的代码,rec_copy()函数中的某些内容无法正常运行,可能是以下行:

  

cp $ 1 / $ f $ HOME / $ 2 / $ dest

名为扩展名的文件夹在目标文件夹中创建,但文件未复制到该位置。你能帮我吗?

#!/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 个答案:

答案 0 :(得分:0)

这是万一有人需要的答案:

#!/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' | sort -u`
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"