Searching Files in Linux

Find command

The following are the Most used search templates for find command:

Search for files only starting with "orapw" pattern:
# find . -name "orapw*" -type f
find / : will search / path.
find . : will search under current working directory.

Search with Ignoring case sensitivity:
# find . -iname "file*"
./file4
./FILE1


Search and Ignore "permission denied" error inside directories not owned by you:
# find /u01/oracle -iname alert_orcl.log  -print 2>/dev/null
-iname                    ignoring case sensitivity.
-print 2>/dev/null   don't print out errors

find the biggest 10 files under the current directory:
# find . -ls | sort -nrk7 | head -10

Search for files bigger than 10m under the current working directory:
# find . -size +10M -exec ls -lh {} \; | awk '{print $5 , $3 , $8 , $9}'

Search for files accessed in the last two days:
# find . -atime 2

Search for files modified in the last two days:
# find . -mtime


LOCATE command

"locate" is much faster than "find" because it searches the database not the Filesystem.
"locate" command is using database file: /var/lib/mlocate/mlocate.db
"locate" command database config file is: /etc/updatedb.conf

In order to make "locate" command more effective, You have to update it's database in a regular basis using this command:
# updatedb

The elapsed time for this command to finish depends on the database if it's recently updated or far old.
Note: In case you want to skip some directories from being scanned and added to the database, you can add the following parameter inside the config fie /etc/updatedb.conf:
e.g. In case you want to skip these directories /tmp  /var/spool  /media:
PRUNEPATHS="/tmp /var/spool /media"

How to use LOCATE command:
# locate -i OC_DATA.dbf
-i     allow using insensitive words + search incomplete words without the need to provide"*".


Searching specific words inside files

Print file names along with the lines that contain keyword "ORA-" inside: [search one level deep]
# grep "ORA-" /home/oracle/*

Print lines contain "ORA-" keyword inside files under /home/oracle along with line number.
# grep -n "ORA-" /home/oracle/*

Print file names that have keyword "dump" inside: [search one level deep]
# grep "dump" /home/oracle/* | cut -d: -f1 

Search multiple words (release, Finish) inside file names start with rmanlog:
# grep 'release\|Finish' /backupdisk/rmanbkps/rmanlog*

Search lines begin with "oracle" keyword inside file db.log:

# grep '^oracle'  db.log

Search lines end with string ";" inside file db.log:
# grep ';$'  db.log

Search and Replace keyword inside files:
e.g. replace word "sea" with word "ocean" in all files with extension .txt
# sed -i 's/sea/ocean/g' *.txt

Delete Lines contain specific pattern:
e.g. delete all lines that have pattern "DBA_BUNDLE1" from files .bash_profile:
# sed -i '/DBA_BUNDLE1/d' .bash_profile


No comments:

Post a Comment