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


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?


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

  • Thanks. But i am actually trying to compress all csv files into the same folder by going inside each folder. – Ubuntuser Sep 5 '13 at 13:36
  • @Ubuntuser And where you said something about this in your question? If you don't see clear, the question is: how to check whether a file is in current directory or subdirectory and if its in a subdirectory, my script should descend to that directory – Radu Rădeanu Sep 5 '13 at 13:38
  • @Ubuntuser If you have another question, please use Ask Ubuntu button. – Radu Rădeanu Sep 5 '13 at 13:41
  • I have asked the question stackoverflow.com/questions/18649393/…. See if you can answer it there :) – Ubuntuser Sep 6 '13 at 3:25
  • 1
    If you mean that directory won't be changed /after/ script execution, this is right. The script is runing in a subshell, and cannot change the parent shell working directory. Replace pwd with comand you want to run inside new directory or source script this way: askubuntu.com/questions/84279/… – sorgel Sep 6 '13 at 5:51
if [ -f t1.csv ]
    echo "File is in target dir"
    cd `dirname $(find . -iname 't1.csv')`
  • I dont think it helps. you see, find command gives the path. So if i do an if statement on the file, it will always find it. I need to check if this file is present in the current directory. – Ubuntuser Sep 6 '13 at 4:45
  • Yes it does: all you need to do extra is check if it has more than 1 backslash ;) (./111/111 versus ./1111) – Rinzwind Sep 6 '13 at 5:28
  • Rinzewind, please tell me more about why more then 1 backslash is needed? – sorgel Sep 6 '13 at 6:03
  • No, find do not test where the command [ -f t1.csv ] does, as can be seen in the code. – MUY Belgium Mar 10 '14 at 14:03

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.