3

I use find to search for files in a directory or its subdirectories. find . -iname '*.csv', and it gives me the following output

./2012/t1.csv
./2012/t2.csv
./2013/t1.csv

Now, I want to check in a script whether the file t1.csv is in the current folder or in one of the subdirectories. If it's in a subdirectory, my script should descend to that directory. How can I do that?

Radu Rădeanu
  • 174,089
  • 51
  • 332
  • 407
Ubuntuser
  • 10,012

3 Answers3

7

To check only for t1.csv, you can use:

find . -name 't1.csv' 

Now, to go in the first directory where t1.csv file is found, you can use:

cd $(dirname $(find . -name 't1.csv' 2>/dev/null | head -1)  2>/dev/null)

enter image description here

Radu Rădeanu
  • 174,089
  • 51
  • 332
  • 407
3
if [ -f t1.csv ]
then
    echo "File is in target dir"
else
    cd `dirname $(find . -iname 't1.csv')`
    pwd
fi
sorgel
  • 439
1

There's a pretty comprehensive discussion on it here:

... see also the grep man pages of course

Not sure about the 2nd part of your question though, but hope that sends you in the right direction.