How to Search a Directory Tree for a Character String
Problem: You have done something unusual in a SAS program or put
someone's name and phone number in a file, but you cannot remember
what file or even which of your directories the file is in.
Solution: Start at your login directory and search all of your files for
that part of the command or name which you can remember.
(Single quotes are used below just to set the command off from the rest of
the line. They are not used when actually issuing the following commands.)
1. Issue the command 'cd' to return to your login directory, or cd to
whichever directory you want to start from.
2. The command 'find ./' will display all file names from there down.
3. If you know that what you are looking for is in a particular type of
file, such as .sas, .txt, .lis, .gz, etc., you can tell 'find' to
return only those types of files by adding '-name "*.extension"' (You
need the double quotes when you use the wildcard '*' but not the
single quotes.)
Now you have:
'find ./ -name "*.sas"' and you get a list of all your .sas programs.
If you specify the full name of the file, leave out the double quotes,
as in:
'find ./ -name oranges.sas'
4. Next you have to look inside each of those files for the information in
which you are interested. The 'grep' command looks into files for
character strings that you specify. The 'zgrep' command looks into
files that have been zipped into .gz files or compressed into .Z
files. An example:
'grep -i libnam *.sas'
'zgrep -i libnam *.sas.gz'
'zgrep -i libnam *.sas.Z'
This looks inside all the .sas files in your current directory for the
character string 'libnam', with the '-i' telling the command to ignore
upper or lower case.
5. To get the 'grep' command to search the output of your 'find' command,
you need to send the output to 'grep' with the '|' (pipe) symbol.
'find ./ -name "*.sas" | grep -i libnam'
This is close, but it will look for 'libnam' in the names of the files,
not the content of the files. (Notice that you do not have to specify
'.sas' on the grep side of the pipe.)
6. To make 'grep' look into the content of the files, add the 'xargs'
command as follows:
'find ./ -name "*.sas" | xargs grep -i libnam'
'find ./ -name "*.sas.gz" | xargs zgrep -i libnam'
'find ./ -name "*.sas.Z" | xargs zgrep -i libnam'
7. Voila! You will get output like this:
./sasconv/conv-tmp-8a.sas:libname x sasv5xpt 'junk.xpt';
./sasconv/test1.sas:libname convert '/home/garcia/irv/datasets';
./sasconv/test1.sas:libname x sasv5xpt 'junk.xpt';
The path and filename are to the left of the colon, and the line in which
the character string appears is to the right.