Linux Command line notes

Search files

Using find

Finding by Name

1
2
find -name "query"
find -iname "query" # ignore case

Finding by Type

1
find -type f # f: regular file, d: directory, l: symbolic link, c character devices, b: block devices

Finding by Time and Size

1
2
3
find -size 50c -mtime 1 # find file size = 50 bytes and modification time of a day ago
find -size +700M -atime +3 # find file size > 700Mb and accessed more than 3 days ago
find -szie -1G -ctime -1 # find file size < 1Gb and changed less than a day ago

Finding by Owner and Permissions

1
find -user syslog -group shadow -perm 664

Filtering by Depth

1
find -name "query" -mindepth 2 -maxdepth 4

Executing and Combining Find Commands

1
find . -type f -perm 644 -exec chmod 664 {} + # {}: a placeholder for files that matches, +: the end of the execute command
1
find -name file1 -or find -name file2

Using locate

The reason locate is faster than find is because it relies on a database of the files on the filesystem. The database is usually updated once a day with a cron script, but you can update it manually by typing:

1
sudo updatedb

To only return files containing the query itself, instead of returning every file that has the query in the directories leading to it, you can use the “-b” for only searching the “basename”:

1
locate -b query

Find and replace specific text in files

find specific text in a file

1
grep -nw filename -e "pattern"

  • -n show line number
  • -w stands for match the whole word

find files containing specific text

1
grep -ril "pattern" path

  • r/R: stands for recursive
  • i: stands for ignore case
  • l: stands for show the file name, not the results itself

replace specific text in a file

1
sed -i 's/original/new/g' file.txt

  • -i = in_place (i.e. save back to the original file)
  • s = the substilte command
  • g = global(i.e. replace all)

replace specific text in files under current directory

1
find . -type f -exec sed -i 's/pattern/new_text/g' {} +