shell实现文件拆分

#!/bin/sh
#方法二
SUFFIX=txt
#源目录:source;目标目录target;每个文件分割的行数:number
#执行程序命令:./test.txt source target 1300000
#校验输入的参数个数($#:这个程序的参数个数,$0:这个程序的名称,$n:这个程序的参数值(0-9))
if [ $# -ne "3" ];then
echo " usage: $0 source_directory desting_directory number "
exit 1
fi

#判断参数1的值是否为目录
if [ ! -d $1 ];then
echo " $1 is not a directory file"
exit 1
fi

#判断参数2的值是否为目录
if [ ! -d $2 ];then
echo " $2 is not a directory file"
exit 1
fi

#循环源目录下的文件
for curfile in $(ls "$1")
do
{
#判断文件是否存在
if [ -e "$1/$curfile" ];then
#basename截断字符串命令
filename=`basename $1/$curfile`

#${filename%.*} 从filename末尾,清除与*匹配的最短部分
file=${filename%.*}

#${file#*.} 从file值开头,清除与*匹配的最短部分
filestr=${file#*.}

#mkdir $2/"$filestr"

#split命令 (语法: split [-bl] 输入文件 输出文件;参数说明:-b :以文件大小来分,-l:以行数来分)
cat $1/$curfile | split -l $3 - "$filestr"_
mv "$filestr"* $2
fi
}
done

for file in $2/*
do
filename=`basename $2/$file`
#file=${filename%.*}
filestr=$filename
#filedir=${filestr/_*/}
#echo $filename
#echo $filedir
fstring=${filestr/#*_/}
#echo $fstring
if [ ! -d $2/"$fstring" ];then
mkdir $2/"$fstring"
fi
mv $file $file.$SUFFIX
mv $file.$SUFFIX $2/"$fstring"
done
echo "Finished...."

#方法二
SUFFIX=txt
if [ $# -ne "3" ];then
echo " usage: $0 source_directory desting_directory number "
exit 1
fi
if [ ! -d $1 ];then
echo " $1 is not a directory file"
exit 1
fi
if [ ! -d $2 ];then
echo " $2 is not a directory file"
exit 1
fi

for curfile in $(ls "$1")
do
{
if [ -e "$1/$curfile" ];then
filename=`basename $1/$curfile`
file=${filename%.*}
filestr=${file#*.}

mkdir $2/"$filestr"
cat $1/$curfile | split -l $3 - "$filestr"_
mv "$filestr"* $2/"$filestr"
fi
}
done

for curfolder in $( ls "$2" )
do
{
for file in $2/$curfolder/*
do
mv $file $file.$SUFFIX
rm -f $file
done
}
done

echo "Finished...."

你可能感兴趣的:(linux)