grep, maybe

Joshua Judson Rosen rozzin at geekspace.com
Thu Oct 29 14:20:33 EDT 2009


mark <prgrmr at gmail.com> writes:
>
> On Thu, Oct 29, 2009 at 11:38 AM, Maurice <mauricep at cds-cumberland.org> wrote:
> 
> > Looking for some guidance;
> >
> > I have several files within several folders (5 files per folder, and
> > thousands of folders) that I need to search a text file within each
> > folder for a word match (like three_little_pigs.txt, and I need to find
> > "moe", if he's listed) and then when a match is found I need to move
> > (not copy) that entire folder (and it's 3~5 files contained within) to
> > another location...
> 
> #!/bin/sh
> cd [top level directory]
> grep -l -r ["search string in double quotes"] > /tmp/file_names_found  2>/tmp/
> grep.errs
> cat /tmp/file_names_found|xargs -i basename {} >/tmp/dir_names_to_move
> dir_list=`sort /tmp/dir_names_to_move|unique`
> for DIRECTORY in $("dir_list"); do
>      mvdir $DIRECTORY [new location here]
>      STATUS=$?
>      if [ $STATUS -ne 0 ]; then
>         echo "mvdir returned status $STATUS"
>      end
> done
> exit


I'd probably go with something like:

    grep --recursive --files-with-matches "$searchstring" "$topdir" \
    | xargs --max-args=1 dirname \
    | sort --unique \
    | xargs mv --target-directory="$newloc"

The only thing that really sucks about that is that the involvement of
`sort' means that the mv needs to wait until *all* of the files have
been grep'd, instead of just moving the directory as soon as *any*
file in it is found to contain the search-term.

And, depending on whether your directories vary in the depth of their
nesting, and whether you prefer to move the more- or less-deep
directories first (or at all), you may need to add a "--reverse" to
the `sort' line or do more complicated filtering with an additional
grep (on the *paths*) or sed.

-- 
Don't be afraid to ask (Lf.((Lx.xx) (Lr.f(rr)))).



More information about the gnhlug-discuss mailing list