I have files as follows in a folder :
Peter_XY.tgz Tom_GF.tgz Harry_AB.tgz
which I am trying to put in different folders based on two txt files that look as follows :
A.txt
AB1
AB
XY
SE
12S
G78
B.txt
OR1
IU345
PIE678
GF
BF
MIL
I am trying to put the files in two different folders :
A
Peter_XY.tgz Harry_AB.tgz
B
Tom_GF.tgz
Now, based on the code suggested here: Move files from one directory to another based on file names in csv using macOS Terminal
I tweaked the code as follows :
for file in $(cat A.txt); do mv $file A; done
for file in $(cat B.txt); do mv $file B; done
How to make sure the code just reads after the '_' sign ?
CodePudding user response:
The following script will look for all files with name ending in .txt
the variable txtFile
in the outer for loop, so A.txt
and B.txt
will be separate loops thru the outer loop.
The inner for loop uses the code you provided to get the charaters after _
but before .tgz
. The variable is seek
.
The basename
w/ extension .txt
of variable txtFile
is used as the destination directory. The variable DEST
, so A.txt
becomes A
.
Finally, any found file matching filename from one of the text files is moved into the destination directory. In other words, mv
(move) *_${seek}.tgz
(any file ending in _
seek
.tgz
) to $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
Here is output given the files you specified above:
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
And the results are like this:
├── A
│ ├── Harry_AB.tgz
│ └── Peter_XY.tgz
├── A.txt
├── B
│ └── Tom_GF.tgz
├── B.txt