Using find will probably return many results, not just one. If you want to perform some operation on each file found, you can do it like this:
Code:
find /home/ -iname '*.txt' |while read filename; do ... done
Where ... are the operations you wish to perform for each file found.
On the other hand, if you want to stop searching after the first file has been located, you can do it like this:
[CODE]find /home/ -iname '*.txt' -print -quit[CODE]
This is a good idea considering how long find can take on large directory structures.
Using basename is OK, but it invokes an external program, which means it is slow / will cause more system load, particularly if you have a lot of files you are interested in. Instead you can use some shell variable expansions to extract parts of the string. In this example. basename1 and basename2 will contain the same result, but the operation used to get basename2 is much faster. The same applies to dirname1 and dirname2.
Code:
mypath="/home/matthew/1/file.txt"
basename1=$(basename "$mypath")
basename2=${mypath##*/}
dirname1=$(dirname "$mypath")
dirname2=${mypath%/*}
You can find detailed descriptions of these and other variable expansions in the "Parameter Expansion" section of the bash manual page.
In summary, a good way to achieve what you describe in the second part of your OP is:
Code:
find /home -iname '*.txt' | while read f
do
b=${f##*/}
d=${f%/*}
echo "File $b is in directory ${d##*/}"
done