I have a directory (directory A) with 10,000 files in it. I want to move some of them to directory B and the others to directory C. I made a text file that contains the names of all the files I want to move to directory B and another one with the names of all the files that I want to move to directory C. How can I write a bash for loop to move these files to the new directories.
Pseudocode:
for file in textfileB:
move file from directory A to directory B
for file in textfileC:
move file from directory A to directory C
Sorry if this is asked somewhere else, but I've spent hours trying to learn bash and I just don't get it. I wasn't able to find something similar enough in another thread that I could understand (maybe I just don't know the right search words).
I got something like this, but I couldn't get it working:
FILES=[dont' know what goes here? An array? A list?
Can I just state the text file name and if so what format do the files have to be? name1.ext, name2.ext, or name1.ext name2.ext]
for f in $FILES; do mv $f /B/$f [not sure about the second argument for mv]; done
thx
BTW Mac OSX 10.6.8 (Snow Leopard) Apple Terminal v. 2.1.2 / 273.1 Bash 3.2
BASH FAQ entry #1: "How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?"
If the filename will remain the same then the second argument to
mv
can be just the directory.you can move 1000 or 1000 user directory without take much time where thousand of user directory exist.
directory of the script should be the your location of the files
You have to use BASH? What about Perl or Kornshell? The problem here is that Bash doesn't have hash keyed arrays (Kornshell and Perl do). That means there's no simple way to track what files go where. Imagine in Perl:
The above lines create two hashes. One for files that need to be moved to Directory B and one for files that need to be moved to Directory C. Now, all I have to do is look at my hash and decide:
My if statements can now look to see if a key has been defined in that hash. If it has, I know the file can be moved into that directory. I only have to read the two text files once. After that, my two hashes will store which files move to one directory and which to the other.
However, we don't have hashes, so we'll use
grep
to see if the file name is in the directory. I'll assume that you have one file name on each line.The
grep -q
will search your two text files to see if the matching file is there. If it is, it'll move the file to that directory. It's not very efficient since it has to search the entire text file each and every time. However, it's pretty efficient, and you're only talking about 10,000 files, so the whole operation should only take a few minutes.Using bash, having a huge filelist containing strings with leading and/or closing spaces I'd propose:
see: