I have a list of patterns in a .txt file. [list.txt]. Foreach line in list.txt, I want to find all the files at a location which begin with the specified pattern in list.txt, and then move these files to another location. Consider an example case.
at ~/home/ana/folder_a
I have list.txt
, which looks like this...
list.txt
1abc
2def
3xyz
At this location i.e /home/ana/folder_a/
, there are multiple files which are beginning with the patterns in list.txt. So, there are files like 1abc_a.txt, 1abc_c.txt, 1abc_f.txt, 2def_g.txt, 3xyz_a.txt
So what I want to achieve is this:
for i in cat list.txt; do
ls | grep '^$i' [thats the pattern] |
mv [files containing the pattern] to /home/ana/folder_b/
Please note that at the other location, i.e /home/ana/folder_b/ I have already created directories, specific for each pattern.
So /home/ana/folder_b/ contains subdirectories like 1abc/ , 2def/ , 3xyz/ In effect, I wish to move all the files matching pattern '1abc', '2def' and '3xyz' from /home/ana/folder_a/ to their respective sub-directories in /home/ana/folder_b/, such that /home/ana/folder_b/1abc will have 1abc_a.txt , 1abc_c.txt , and 1abc_f.txt ; /home/ana/folder_b/2def/ will have 2def_g.txt and /home/ana/folder_b/3xyz/ will have 3xyz_a.txt
i'd suggest using the
-exec
action offind
to callmv
in your loop.beginning file structure: (as you can see, i'm calling this from the parent of folder_a and folder_b)
command:
alternate command (same thing, just all on one line):
resulting file structure:
Grep's
-f
option matches patterns from a file so you don't have to loop over each line in the file inshell
:Pipe to
xargs
to do the move:Edit: Realised I missed the subdirectory part of the question, @Thor's answers is the best approach for this, still I think you might find some use from this answer.
I think glob expansion is the way to go here:
Start with an
echo
in front of themv
command, and remove it when you're happy with the output.