一次将一个文件移动到另一个目录,提取文件名的一部分,然后在所有文件移动后停止



我在源目录中有n个文件(c: srcdir(示例:

837_FILE
845_FILE

我想一次将一个文件移至目标目录(c: tgtdir(并从文件名中获取前3个字符,然后在Linux脚本中跳到该功能。

我尝试了以下脚本

#!/bin/sh
cd `dirname $0`
srcdir=`C:SRCDIR`
tgtdir=`C:TGTDIR`
837()
{
echo "this is 837 file"
}
845()
{
echo "this is 845 file"
}
filecount=$(find $srcdir -maxdepth 1 -type f -name '*.*' | wc -l)
if [ $filecount -gt 0 ] ; then
## want to loop here like, take one file at a time 
## move to target location
## take first three characters of a file and go to that function (837, 845)
## loop until end of files
fi

如何用于循环?

#!/bin/sh
srcdir="/tmp/src"
tgtdir="/tmp/tgt"
refdir="/tmp/ref"
for filename in ${srcdir}/*; do
    first_3_chars=`echo $(basename ${filename}) | cut -c1-3`;
    wc -l ${refdir}/${first_3_chars}
    mv ${filename} ${tgtdir};
done

测试数据:

florin@debian:/tmp$ ll src/
total 0
-rw-r--r-- 1 florin florin 0 iul 30 21:37 280_FILE
-rw-r--r-- 1 florin florin 0 iul 30 21:37 837_FILE
-rw-r--r-- 1 florin florin 0 iul 30 21:37 845_FILE
florin@debian:/tmp$ ll tgt/
total 0
florin@debian:/tmp$ ll ref/
total 4
-rw-r--r-- 1 florin florin 5 iul 30 21:52 280
-rw-r--r-- 1 florin florin 0 iul 30 21:38 837
-rw-r--r-- 1 florin florin 0 iul 30 21:38 845

运行示例:

florin@debian:/tmp$ ./test.sh 
1 /tmp/ref/280
0 /tmp/ref/837
0 /tmp/ref/845
florin@debian:/tmp$ ll src/
total 0
florin@debian:/tmp$ ll tgt/
total 0
-rw-r--r-- 1 florin florin 0 iul 30 21:37 280_FILE
-rw-r--r-- 1 florin florin 0 iul 30 21:37 837_FILE
-rw-r--r-- 1 florin florin 0 iul 30 21:37 845_FILE
#!/bin/sh
cd `dirname $0`
prntdir=`pwd`
f837()
{
 echo "this is 837 file $filename"
}
f270()
{
 echo "this is 270 file $filename"
}
filecount=$(find $prntdir/srcdir -maxdepth 1 -type f -name '*.*' | wc -l)
if [ $filecount -gt 0 ] ; then
        for filepath in $prntdir/srcdir/*; do
        filename=$(basename $filepath)
        echo $filename
        mv $prntdir/srcdir/$filename $prntdir/tgtdir/$filnename
        first_3_chars=f`echo $filename | cut -c1-3`;
        $first_3_chars
        done
else
   echo "no files exist for processing"
fi

最新更新