Reputation: 113
I am trying to write a bash script that will allow me to grab the names of files on Dir1 for example, and use EACH file name as my search string in the find command, and run the find command on Dir2. Then, output the search results to a text file.
So, for example, when it runs it will:
Get files in Dir1:
- file1.txt
- file2.txt
- file3.txt
- file4.txt
Find any files in Dir2 with "file1" in name
file1 exists in Dir2 as "file1-extrafile.txt"
Write result to text file
Repeat using "file2" as search string.
How can I do this? Will diff
help me? A for
loop?
Upvotes: 1
Views: 3805
Reputation: 20869
find Dir1 -type f -printf '%f\0' | xargs -0 -n1 find Dir2 -name
Given files:
Dir1/a/b/c
Dir1/a/d
Dir1/e
Dir2/a/b
Dir2/a/e
Dir2/d
Dir2/c
Dir2/e/f
Will print:
Dir2/c
Dir2/d
Dir2/a/e
Dir2/e
Upvotes: 1
Reputation: 23562
Put this in a file (say search.sh
) and execute it with ./search.sh dir1 dir2
#!/bin/sh
dir1=$1
dir2=$2
[ -z "$dir1" -o -z "$dir2" ] && echo "$0 dir1 dir2" 1>&2 && exit 1
#
# Stash contents of dir2 for easy searching later
#
dir2cache=/tmp/dir2.$$
# Clean up after ourselves
trap "rm -f $dir2cache" 0 1 2 15
# Populate the cache
find $dir2 -type f > $dir2cache
#
# Iterate over patterns and search against cache
#
for f in $(find $dir1 -type f); do
# Extract base name without extension
n=$(basename $f .txt)
# Search for files that begin with base name in the cache
fgrep "/$n" $dir2cache
done
Upvotes: 0
Reputation: 200523
Try this:
for f in /dir1/*; do
n=$(basename "$f")
ls -1 /dir2/*${n%.*}*.${n##*.}
done > result.txt
Upvotes: 1