shell 根据csv文件中文件名匹配的字符串子集将文件移动到不同的目录

4dbbbstv  于 2022-11-25  发布在  Shell
关注(0)|答案(1)|浏览(214)

我在文件夹中有以下文件:

Peter_XY.tgz Tom_GF.tgz Harry_AB.tgz

我尝试根据两个txt文件将其放在不同的文件夹中,如下所示:

A.txt 
AB1
AB
XY
SE
12S
G78

B.txt

OR1
IU345
PIE678
GF
BF
MIL

我尝试将文件放在两个不同的文件夹中:

A 
Peter_XY.tgz Harry_AB.tgz

B
Tom_GF.tgz

现在,根据此处建议的代码:Move files from one directory to another based on file names in csv using macOS Terminal
我对代码进行了如下调整:

for file in $(cat A.txt); do mv $file A; done
for file in $(cat B.txt); do mv $file B; done

如何确保代码只在“_”符号之后读取?

wrrgggsh

wrrgggsh1#

下面的脚本将在外部for循环中查找所有名称以.txt结尾的文件(变量txtFile),因此A.txtB.txt将是通过外部循环的独立循环。
内部for循环使用您提供的代码来获取_之后.tgz之前的字符。变量为seek
变量txtFile的扩展名为.txtbasename用作目标目录。变量DEST,因此A.txt变为A
最后,从其中一个文本文件中找到的任何与文件名匹配的文件都被移动到目标目录中。换句话说,mv(移动)*_${seek}.tgz(任何以_seek.tgz结尾的文件)到$DEST

for txtFile in *.txt ; do
   DEST=$(basename $txtFile .txt);
   echo "processing $txtFile by moving matches to $DEST";
   for seek in $(cat $txtFile) ; do
     echo "Moving files matching *_${seek}.tgz to $DEST";
     mv *_${seek}.tgz $DEST;
   done;
done

以下是您在上面指定的文件的输出:

processing A.txt by moving matches to A
Moving files matching *_AB1.tgz to A
mv: rename *_AB1.tgz to A/*_AB1.tgz: No such file or directory
Moving files matching *_AB.tgz to A
Moving files matching *_XY.tgz to A
Moving files matching *_SE.tgz to A
mv: rename *_SE.tgz to A/*_SE.tgz: No such file or directory
Moving files matching *_12S.tgz to A
mv: rename *_12S.tgz to A/*_12S.tgz: No such file or directory
Moving files matching *_G78.tgz to A
mv: rename *_G78.tgz to A/*_G78.tgz: No such file or directory
processing B.txt by moving matches to B
Moving files matching *_OR1.tgz to B
mv: rename *_OR1.tgz to B/*_OR1.tgz: No such file or directory
Moving files matching *_IU345.tgz to B
mv: rename *_IU345.tgz to B/*_IU345.tgz: No such file or directory
Moving files matching *_PIE678.tgz to B
mv: rename *_PIE678.tgz to B/*_PIE678.tgz: No such file or directory
Moving files matching *_GF.tgz to B
Moving files matching *_BF.tgz to B
mv: rename *_BF.tgz to B/*_BF.tgz: No such file or directory
Moving files matching *_MIL.tgz to B
mv: rename *_MIL.tgz to B/*_MIL.tgz: No such file or directory

而结果是这样的:

├── A
│   ├── Harry_AB.tgz
│   └── Peter_XY.tgz
├── A.txt
├── B
│   └── Tom_GF.tgz
├── B.txt

相关问题