chmod, find, locate, grep & sed

μž‘μ„±μž

μΉ΄ν…Œκ³ λ¦¬:

← ν”Όλ“œλ‘œ
DEV Community · Tejas Shinkar · 2026-06-18 개발(SW)

πŸ“Œ What’s covered in this session

  • chmod β€” symbolic and numeric permissions (full coverage)
  • User management basics β€” /etc/passwd, creating users
  • find β€” searching files by name, type, size, owner, and executing actions
  • locate vs find β€” when to use which
  • grep β€” searching inside files, pipes, counting, log analysis
  • sed β€” find & replace, delete lines, insert lines, in-place editing

01 β€” chmod (Deeper Coverage)

We covered numeric permissions in Session 3. Session 4 adds symbolic permissions β€” a more readable way to set permissions without calculating numbers.

Symbolic Permission Syntax

chmod  [who][operator][permission]  file

Enter fullscreen mode Exit fullscreen mode

Symbol Meaning u user (owner) g group o others a all (u + g + o) + add permission - remove permission = set exactly this permission

Symbolic chmod Examples

Command What it does chmod g-w file.txt Remove write permission from group chmod u+x file.txt Give execute permission to owner chmod o+r file.txt Give read permission to others chmod a+rwx file.txt Give read, write, execute to everyone chmod ugo+rwx file.txt Same as above β€” explicit version

Numeric chmod (Recap + Examples)

r = 4,  w = 2,  x = 1

Enter fullscreen mode Exit fullscreen mode

Command Breakdown What it gives chmod 741 file.txt 7=rwx, 4=r–, 1=–x Owner: full, Group: read only, Others: execute only chmod 600 file.txt 6=rw-, 0=—, 0=— Owner: read+write, nobody else has any access chmod 755 script.sh 7=rwx, 5=r-x, 5=r-x Owner: full, Group+Others: read+execute chmod 644 file.txt 6=rw-, 4=r–, 4=r– Owner: read+write, everyone else: read only

☁️ DevOps Context β€” Access Control

In real server environments, permissions are part of Access Control. Think of it like this: a temporary contractor employee joins the project. You give them access to only the files they need β€” with an expiry. When they leave, you remove access.

  • Temporary user β†’ create user, add to group, set password expiry
  • Specific access β†’ set file permissions for that group

– Access removed β†’ delete user or remove from group

02 β€” User Management Basics

/etc/passwd β€” Reading User Info

cat /etc/passwd

Enter fullscreen mode Exit fullscreen mode

Each line in /etc/passwd has 7 fields separated by ::

username:password:UID:GID:comment:home_dir:shell

# Example:
tejas:x:1001:1001:Tejas:/home/tejas:/bin/bash
root:x:0:0:root:/root:/bin/bash
nginx:x:110:118::/var/lib/nginx:/usr/sbin/nologin

Enter fullscreen mode Exit fullscreen mode

Field What it means username Login name password x means password is stored in /etc/shadow UID User ID β€” root is always 0 GID Primary Group ID comment Full name or description home_dir User’s home directory shell Shell assigned β€” /usr/sbin/nologin = service account, can’t login

Creating a New User

sudo useradd new_user          # create the user
sudo passwd new_user           # set a password for the user

Enter fullscreen mode Exit fullscreen mode

After running passwd, it prompts you to enter and confirm the new password.

What Ctrl+Z does in Background

Shortcut What it does Ctrl+Z Suspends (pauses) the current foreground process, puts it in background bg Resumes a suspended process in the background fg Brings a background process back to foreground jobs Lists all background/suspended jobs
# Example:
tail -f /var/log/syslog    # running in foreground
# press Ctrl+Z             β†’ process is suspended
bg                         # resume it in background
fg                         # bring it back to foreground

Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Useful when you start a long-running command and need your terminal back without killing it.

03 β€” find

find searches live inside the filesystem β€” it scans directories in real time. Slower than locate but always accurate and highly flexible.

Basic Syntax

find  [where to search]  [what to search by]  [condition]

Enter fullscreen mode Exit fullscreen mode

Find by Name

Command What it does find /home -name file.txt Find file.txt in /home and all subdirectories (case sensitive) find /home -iname file.txt Same but case insensitive find . -name "*.txt" Find all .txt files in current directory and below find . -name "*.log" Find all log files recursively from current dir

Find by Type

Command What it does find /var -type f List only regular files inside /var find /var -type d List only directories inside /var find . -type d -name find.dir Find a directory named find.dir from current location

Find by Size

Command What it does find /home -size +10M Files larger than 10MB find . -size -1k Files smaller than 1KB in current directory find . -size 5M Files exactly 5MB

Size units: c=bytes, k=kilobytes, M=megabytes, G=gigabytes

Find by Owner

Command What it does find /home -user tejas All files owned by user tejas find /var -user root All files owned by root in /var

Find + Action (One-liners)

This is where find gets powerful β€” you can act on results directly.

Command What it does find . -name "*.tmp" -delete Find all .tmp files and delete them permanently find . -name "*.log" -delete Find and delete all log files in current dir find /home -name "prakhar.txt" Searches /home recursively, returns path if found
# How find searches recursively:
find /home -name "prakhar.txt"
# β†’ checks /home
# β†’ checks /home/1/
# β†’ checks /home/2/
# β†’ checks /home/3/
# β†’ checks /home/4/
# β†’ checks /home/5/   β†’ prakhar.txt found β†’ it prints the path

Enter fullscreen mode Exit fullscreen mode

☁️ DevOps Context β€” Disk Cleanup & Auditing

find is essential for server maintenance:

# Find files larger than 500MB (disk space investigation)
find / -size +500M -type f

# Find and delete all tmp files older than 7 days
find /tmp -type f -mtime +7 -delete

# Find files with dangerous open permissions
find / -type f -perm 777

# Find all .pem key files (security audit)
find /home -name "*.pem"

04 β€” locate

locate searches a pre-built database of file paths β€” it does not scan the filesystem live.

find vs locate β€” Side by Side

find locate How it works Scans filesystem live Searches a pre-built database Speed Slower Much faster Accuracy Always accurate May be outdated New files Shows immediately Won’t show until DB is updated Needs install No β€” built-in Sometimes: sudo apt install plocate DB update N/A sudo updatedb

The “New File Problem” with locate

touch newfile.txt
locate newfile.txt    # ← won't find it yet β€” DB is stale

sudo updatedb         # ← update the database manually
locate newfile.txt    # ← now it finds it

Enter fullscreen mode Exit fullscreen mode

The database updates automatically on a schedule (daily cron job), but if you just created a file, run sudo updatedb first.

locate Commands

Command What it does locate file.txt Find path of file.txt from the database locate -i file.txt Case insensitive search locate -c passwd Count how many matching paths exist (no output, just number) locate *.log Find all files with .log extension

05 β€” grep

grep searches inside files for a pattern and prints matching lines. One of the most used commands in DevOps for log analysis.

Basic grep

Command What it does grep "has" file.txt Print all lines containing “has” (case sensitive) grep -i "has" file.txt Case insensitive search grep -n "has" file.txt Print matching lines with their line numbers grep -c "has" file.txt Count how many lines contain “has” (1 per line, even if “has” appears multiple times) grep -ci "has" file.txt Count matches, case insensitive grep -o "has" file.txt Print only the matching word, one per match (not the full line)

⚠️ grep -c counts lines, not occurrences. If “has” appears 3 times on one line, it still counts as 1.

grep with Pipe

cat file.txt | grep "has"    # same result as grep "has" file.txt, less efficient

Enter fullscreen mode Exit fullscreen mode

Prefer grep "has" file.txt directly β€” no need for cat when grep can read the file itself.

grep + wc (Word Count)

wc counts lines, words, or characters. Combined with grep it becomes powerful:

Command What it does `grep “has” file.txt \ wc -l` `grep “has” file.txt \ wc -w` `grep “has” file.txt \ wc -c`

grep for Log Analysis β€” DevOps Use Case

# Search for errors in syslog
grep "error" /var/log/syslog

# Case insensitive error search
grep -i "error" /var/log/syslog

# Show line numbers alongside errors
grep -n "error" /var/log/syslog

# Count how many error lines exist
grep -c "error" /var/log/syslog

# Live log + filter errors simultaneously
tail -f /var/log/syslog | grep "error"

# Search for errors across multiple log files
grep -r "ERROR" /var/log/nginx/

Enter fullscreen mode Exit fullscreen mode

☁️ DevOps Context β€” Log Analysis

grep is the fastest way to triage incidents on a Linux server without any extra tools:

# Is nginx throwing 502 errors?
grep "502" /var/log/nginx/access.log

# How many errors in the last deploy?
grep -c "ERROR" /var/log/app/deploy.log

# Find which IP is causing most errors
grep "400" /var/log/nginx/access.log | wc -l

In production, you’d use tools like CloudWatch, Datadog, or ELK stack β€” but when you SSH into a box at 2am during an incident, grep is what saves you.

06 β€” sed (Stream Editor)

sed edits text in a stream or file β€” find and replace, delete lines, insert lines. It doesn’t open the file in an editor; it processes it line by line.

sed Syntax

sed  '[line/pattern][command]'  file.txt

Enter fullscreen mode Exit fullscreen mode

Find and Replace

Command What it does sed 's/has/have/' file.txt Replace first “has” with “have” on each line sed 's/has/have/g' file.txt Replace all “has” with “have” globally (every occurrence) sed 's/has/have/gI' file.txt Replace all occurrences, case insensitive sed -i 's/has/have/gI' file.txt Make the change permanently in the original file sed '2s/has/have/g' file.txt Replace only on line 2 sed '2,5s/has/have/g' file.txt Replace in line range 2 to 5 only

⚠️ Without -i, sed only prints the result to terminal β€” the original file is NOT changed. Add -i to edit in place.

Delete Lines

Command What it does sed '3d' file.txt Delete line 3 sed '3,5d' file.txt Delete lines 3 to 5 sed '/have/d' file.txt Delete all lines that contain the pattern “have”

Print Specific Lines

Command What it does sed -n '5p' file.txt Print only line 5 sed -n '2,6p' file.txt Print lines 2 to 6 sed -n '/have/p' file.txt Print only lines containing “have”

Insert and Append Lines

Command What it does sed '2i i have inserted this line' file.txt Insert a new line before line 2 sed '2a i have appended this' file.txt Append a new line after line 2 sed 'a i have appended this' file.txt Append after every line (no line number = all lines) sed '4c i have replaced this line' file.txt Replace entire line 4 with new content

☁️ DevOps Context β€” Config File Automation

sed -i is used extensively in automation scripts to modify config files without opening an editor:

# Change port in nginx config
sed -i 's/listen 80/listen 8080/g' /etc/nginx/nginx.conf

# Replace DB host in app config during deployment
sed -i 's/localhost/prod-db.internal/g' /opt/app/config.yaml

# Comment out a line in a config file
sed -i 's/^SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config

# Remove all blank lines from a file
sed -i '/^$/d' config.txt

This is how Ansible shell tasks and deployment scripts modify configs on servers without human intervention.

⚑ Quick Revision

Concept One-liner chmod g-w Remove write from group. Symbolic notation. chmod u+x Add execute to owner. Most common for scripts. chmod 600 Owner read+write only. Use for private keys, secrets. chmod 741 Owner full, group read, others execute. Can’t chmod inside dir Navigate out first, then apply chmod to the directory. find Live filesystem scan. Slow but always accurate. find . -type f Find only regular files from current dir. find . -type d Find only directories from current dir. find -size +10M Find files larger than 10MB. find -name "*.tmp" -delete Find and delete in one command. locate Database search. Fast but may be stale. sudo updatedb Refresh locate database after creating new files. grep "pattern" file Search inside a file, print matching lines. grep -i Case insensitive grep. grep -n Show line numbers with results. grep -c Count matching lines (not occurrences). `grep \ wc -l` grep "error" /var/log/syslog Standard log error search. sed 's/old/new/g' Replace all occurrences in output. sed -i 's/old/new/g' Replace in file permanently. sed '3d' Delete line 3. sed -n '5p' Print only line 5.

🎯 Interview Points

Q: What is the difference between symbolic and numeric chmod?

Both change file permissions. Numeric (chmod 755) uses octal numbers β€” you set the complete permission for all three entities at once. Symbolic (chmod u+x) is more readable β€” you target a specific entity (u/g/o/a) and add or remove a specific permission. Symbolic is useful when you want to change one permission without affecting others.

Q: What is the difference between find and locate?

find scans the live filesystem in real time β€” always accurate but slower. locate queries a pre-built database β€” much faster but can be outdated. If you create a file and immediately run locate, it won’t appear until sudo updatedb is run. Use find for accuracy, locate for quick path lookups of stable files.

Q: How would you find and delete all .tmp files on a server?

find / -name "*.tmp" -delete. Or safer: first run find / -name "*.tmp" to preview, then add -delete. For temporary files older than N days: find /tmp -type f -mtime +7 -delete.

Q: What does grep -c count β€” lines or occurrences?

Lines. If a pattern appears 5 times on one line, grep -c counts it as 1. Use grep -o "pattern" file | wc -l if you need to count every individual occurrence.

Q: What is the difference between sed 's/old/new/' and sed 's/old/new/g'?

Without g, sed replaces only the first occurrence on each line. With g (global flag), it replaces every occurrence on every line. Without -i, the original file is not modified β€” output goes to terminal only. Add -i to edit the file in place.

Q: How would you use grep to investigate an incident on a production server?

grep -i "error" /var/log/app/app.log to find error lines. grep -c "ERROR" /var/log/app/app.log to count them. tail -f /var/log/app/app.log | grep "ERROR" to watch live. grep -n "500" /var/log/nginx/access.log to find the line numbers of 500 errors in nginx.

Q: What does sed -i do and why is it important in automation?

-i tells sed to edit the file in place β€” the original file is modified permanently. Without it, changes only print to stdout. In DevOps automation scripts and Ansible tasks, sed -i is used to modify config files on servers without opening an editor, enabling fully automated configuration management.

πŸ“‹ Knowledge Base β€” Quick Reference

# ── chmod symbolic ─────────────────────────────────────
chmod u+x file.sh             # add execute to owner
chmod g-w file.txt            # remove write from group
chmod o+r file.txt            # add read to others
chmod a+rwx file.txt          # give everyone full access
chmod ugo+rwx file.txt        # same as above

# ── chmod numeric ──────────────────────────────────────
chmod 600 key.pem             # owner rw only (secrets, SSH keys)
chmod 644 file.txt            # owner rw, others r (config files)
chmod 755 script.sh           # owner rwx, others rx (scripts)
chmod 741 file.txt            # owner full, group r, others x

# ── User management basics ─────────────────────────────
cat /etc/passwd               # view user accounts
sudo useradd username         # create new user
sudo passwd username          # set password for user

# ── find ───────────────────────────────────────────────
find /home -name "file.txt"   # find by name (case sensitive)
find /home -iname "file.txt"  # case insensitive
find . -name "*.log"          # find by extension
find /var -type f             # files only
find /var -type d             # directories only
find /home -size +10M         # files > 10MB
find /home -size -1k          # files < 1KB
find /home -user tejas        # files owned by user
find . -name "*.tmp" -delete  # find and delete

# ── locate ─────────────────────────────────────────────
locate file.txt               # fast path lookup
locate -i file.txt            # case insensitive
locate -c passwd              # count matches only
sudo updatedb                 # refresh database

# ── grep ───────────────────────────────────────────────
grep "error" file.txt         # search in file
grep -i "error" file.txt      # case insensitive
grep -n "error" file.txt      # show line numbers
grep -c "error" file.txt      # count matching lines
grep -o "error" file.txt      # print only match, not full line
grep "error" /var/log/syslog  # log error search ⭐
tail -f app.log | grep "ERROR" # live error stream ⭐
grep "error" file.txt | wc -l # count via pipe
grep "error" file.txt | wc -w # word count of matched lines

# ── sed ────────────────────────────────────────────────
sed 's/old/new/' file.txt        # replace first match per line
sed 's/old/new/g' file.txt       # replace all (global)
sed 's/old/new/gI' file.txt      # global, case insensitive
sed -i 's/old/new/g' file.txt    # replace in file permanently ⭐
sed '2s/old/new/g' file.txt      # replace on line 2 only
sed '2,5s/old/new/g' file.txt    # replace in line range
sed '3d' file.txt                # delete line 3
sed '3,5d' file.txt              # delete lines 3-5
sed '/pattern/d' file.txt        # delete lines matching pattern
sed -n '5p' file.txt             # print only line 5
sed -n '2,6p' file.txt           # print line range
sed -n '/pattern/p' file.txt     # print lines matching pattern
sed '2i new line here' file.txt  # insert before line 2
sed '2a new line here' file.txt  # append after line 2
sed '4c replacement line' file.txt # replace entire line 4

Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Takeaway

Session 4 introduced the tools DevOps engineers use every single day β€” not just on their own machines but on remote servers at 2am during incidents. grep and sed in particular are the difference between an engineer who can work effectively on any Linux server with zero extra tools, and one who needs a GUI or a full observability stack before they can do anything. These commands are small, composable, and when chained with pipes they become genuinely powerful. The pattern of find β†’ grep β†’ sed β€” locate the files, search inside them, modify them β€” is at the core of most server automation tasks.

πŸ’¬ Learning Linux for DevOps & Cloud. Drop a comment if you have questions or spot something β€” always open to feedback.

μ›λ¬Έμ—μ„œ 계속 β†—

μΆ”μΆœ λ³Έλ¬Έ Β· 좜처: dev.to Β· https://dev.to/tejas_shinkar/chmod-find-locate-grep-sed-1h9o

μ½”λ©˜νŠΈ

λ‹΅κΈ€ 남기기

이메일 μ£Όμ†ŒλŠ” κ³΅κ°œλ˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€. ν•„μˆ˜ ν•„λ“œλŠ” *둜 ν‘œμ‹œλ©λ‹ˆλ‹€