所以我有一个像这样的文件结构:
123-12345-00.sct 123-12345-00.mot 123-12345-01.mot 123-12345-02.mot 123-12345-03.mot 123-12345-04.mot 123-12345-05.mot 123-12346-00.sct 123-12346-00.mot 123-12346-01.mot 123-12346-02.mot 123-12346-03.mot 123-12346-04.mot 123-12346-05.mot
等等。需要随机选择文件.sct并将其及其相关文件移动到另一个目录。希望我已经解释得这么好了。
感谢您的帮助。我可以在VB中做到这一点,但这个UNIX的东西让我感到难过。现在我们通过数千个文件手动完成。
斯科特
答案 0 :(得分:1)
此脚本将123-12345-*.sct
和123-12345-*.mot
文件移动到名为123-12345
的目录,依此类推。
注意:这不会随机选择文件,而是目录中的所有文件。您可以修改此项以接受随机文件数的命令行参数。然后,您需要修改此命令ls [0-9]*.sct | grep -oe '[0-9]\{3\}\-[0-9]\{5\}'
以使用命令行参数,该参数是文件计数并返回随机数量的前缀。
将下面的内容复制到一个文件中,在与sct和mot文件相同的目录中说mv_sct_mot.sh
。
#!/bin/bash
for prefix in `ls [0-9]*.sct | grep -oe '[0-9]\{3\}\-[0-9]\{5\}'`; do
mkdir -p ${prefix};
mv ${prefix}-*.{mot,sct} ${prefix};
done
要使文件可执行,请修改它的权限,如:
chmod +x mv_sct_mot.sh
像以下一样运行:
./mv_sct_mot.sh
答案 1 :(得分:1)
#! /usr/bin/env bash
dir="$1"
count="$2"
[ "$dir" ] && [ $count -gt 0 ] && {
if [ ! -d "$dir" ]; then echo "$0: $dir: no such directory"; exit; fi;
RANDOM=$(date +%s) #init random seed
for (( c=0; c < $count; c++ )); do
files=(*.sct) #creates array of sct files
ct=${#files[@]} #computes array length
if [ $ct -eq 0 ]; then break; fi #no more .sct file, exiting
sct=${files[$[($RANDOM % $ct)]]} #pick random file
# You might want to change this according to your file names
# Everything before the last dash `-' (included) will be taken
# as prefix
prefix=$(echo $sct | sed 's:\(.*-\).*:\1:')
mot_files=($prefix*.mot) #creates array of all matching .mot
mv $sct $dir #moves .sct to $dir
if [ ${#mot_files[@]} -gt 0 ]; then
mv ${mot_files[@]} $dir #moves each matching .mot to $dir
fi
done
} || echo "usage: $0 <dir> <num of files>"
会这样做。
/tmp/r > ls 123-12345-00.mot 123-12345-05.mot 123-12346-04.mot 123-12345-00.sct 123-12346-00.mot 123-12346-05.mot 123-12345-01.mot 123-12346-00.sct 123-12348-00.mot 123-12345-02.mot 123-12346-01.mot 123-12348-00.sct 123-12345-03.mot 123-12346-02.mot foo 123-12345-04.mot 123-12346-03.mot /tmp/r > mkdir bar /tmp/r > ./foo bar 2 /tmp/r > ls 123-12346-00.mot 123-12346-02.mot 123-12346-05.mot 123-12346-00.sct 123-12346-03.mot bar 123-12346-01.mot 123-12346-04.mot foo /tmp/r > ls bar 123-12345-00.mot 123-12345-02.mot 123-12345-05.mot 123-12345-00.sct 123-12345-03.mot 123-12348-00.mot 123-12345-01.mot 123-12345-04.mot 123-12348-00.sct
答案 2 :(得分:0)
以下是我如何做到这一点:
#!/bin/bash
## use the first param as count (1 as default value)
count=${1:-1}
## list all .sct files, random sort and pick the first $count
ls $SRCDIR/*.sct | sort -R | head -n $count |
while read file; do
## for each file, figure out the prefix and move prefix*
prefix="${file%-*}-"
mv -v $prefix* $DESTDIR
done
编辑:我最初错过了文件数量是参数的部分,现在更新了脚本。为了清楚起见,我浏览了设置SRCDIR和DESTDIR的部分。