Wednesday 1 March 2023

FINDING A MISSED FILE IN THE PC BY THE SHELL

 

Have you ever created a file and forgotten where you saved it and its name?


You might want to search it through the last modification date
In Windows it can be tricky, but with Git Bash can be very easy and fast (in Linux should work as well).

At the end of the post you can find the recap of the code!


Firstly, open Git Bash directly in the main directory you want to search for the file.
In this example, I opened it in the directory called Shell, since my file is there, somewhere.

Now, you make a list ('ls') of all the files in this directory and its subdirectories, which displays also the last modification date.
However, you do not want to see this list (it might be very long!), but search in it and see only the wanted results.
Hence, you'll use the pipe ('|') to concatenate the command 'grep' and search by date:

    ls -lR | grep 'Feb 23'

# the -l flag gives you a list that includes the last modification date
# the -R flag is for searching all the subdirectories 


Pay attention when writing the date! The format should be:

        abbreviation of the month + space + 2 numbers for the day +  space + year 

but if the number for the day is only one, then use 2 spaces:
    
    'Feb  3  2023'

You are not obliged to use all these elements, you can choose. But be sure it is the same format as the output of 'ls -l' or you'll get no results. You can have an idea of it just doing:

    ls -l    #it will list the files in the working directory


This is what you get:



The arrow indicates the file we are looking for.


Now you want to know the path of the file, to find it. Use the 'find' command and pass to it the name of the file just found (copy/paste):

    find -name 'shell_data.tar.gz'



It gives you the RELATIVE PATH so now you can find the file!


If you want the FULL PATH, you need to navigate to the folder with 'cd' and use the 'readlink' command with the '-f' flag:

    cd 'Shell lessons -Carpentry_2023'/'materiale per lezione'
    readlink -f 'shell_data.tar.gz'
 



Now you can even copy/paste the path in the windows bar, press Enter and it will bring you to the folder with the file.

Easy, right?

This is the recap of the code:

ls -lR | grep 'dateInTheSameFormatOfTheOutputOf_ls'
find -name 'FileName'

#optional:
cd 'relativePath'
readlink -f 'FileName'


I hope it makes your day!
If you have a better solution, I am curious to hear about it.