Toadman30 Toadman30 - 7 months ago 17
Bash Question

iterate over lines in file then find in directory

I am having trouble looping and searching. It seems that the loop is not waiting for the find to finish. What am I doing wrong?

I made a loop the reads a file line by line. I then want to use that "name" to search a directory looking to see if a folder has that name. If it exists copy it to a drive.

#!/bin/bash

DIRFIND="$2"
DIRCOPY="$3"

if [ -d $DIRFIND ]; then

while IFS='' read -r line || [[ -n "$line" ]]; do
echo "$line"

FILE=`find "$DIRFIND" -type d -name "$line"`

if [ -n "$FILE" ]; then
echo "Found $FILE"
cp -a "$FILE" "$DIRCOPY"
else
echo "$line not found."
fi

done < "$1"
else
echo "No such file or directory"
fi

Answer

Have you tried xargs...

Proposed Solution

cat filenamelist | xargs -n1 -I {} find . -type d -name {} -print | xargs -n1 -I {} mv {} . 

what the above does is pipe a list of filenames into find (one at a time), when found find prints the name and passes to xarg which moves the file...

Expansion

file = yogo

yogo -> | xargs -n1 -I yogo find . -type d -name yogo -print | xargs -n1 -I {} mv ./<path>/yogo . 

I hope the above helps, note that xargs has the advantage that you do not run out of command line buffer.