Skip to content
LIVE FEED

BlogLinux/Ubuntu Commands - Tổng Hợp Toàn Diện

Bố cục bài viết

Linux/Ubuntu Commands - Tổng Hợp Toàn Diện Table of Contents 1. Tìm Kiếm Files (find) Cơ bản Tìm theo thời gian Tìm theo kích thước Tìm theo user/permissions Combinations (AND/OR) Action (-exec / -delete) Example commands 2. Đếm Số Lượng Files Đơn giản Dùng find Advanced counting 3. Kiểm Tra Dung Lượng Files Size của file/folder Disk usage overview Find files by size Detailed size report 4. Tìm Text trong Tài Liệu (grep) Cơ bản Tìm trong multiple files Context lines Regular expressions Useful flags Pipe with other commands 5. Quản lý Files & Directories Liệt kê files Thay đổi thư mục Tạo/Xóa Copy/Move Xem nội dung 6. Quản lý Users & Permissions User info Tạo/Xóa user Permissions (rwx) sudo (SuperUser DO) 7. Quản lý Packages (apt) Update/Upgrade Install/Remove Repository 8. Quản lý Services Systemctl (systemd) Service logs 9. Networking IP/Network info Ping/Trace Port/Service DNS SSH 10. Disk & Storage Disk usage Mount/Unmount Disk check 11. Process Management List processes Kill process Background/Foreground 12. Text Processing Search & Replace Grep variants Sorting/Unique Cut/Awk/Paste Other 13. Compression Tar (archive) Zip Gzip Individual file compression 14. System Info & Monitoring System info CPU info Temperature Logs 15. Useful Shortcuts & Tips History Aliases (thêm vào ~/.bashrc hoặc ~/.zshrc) Quick commands Piping & Redirection Variables 16. Advanced/Useful Commands System updates Create file Download Cron (scheduled tasks) Watch command changes Benchmark File size 17. Practical Examples Find & Count Files > 100MB List 10 Largest Files Find All .log Files, > 1MB, Modified in Last 7 Days Count Files by Extension Find Text in All Config Files Find Errors in Logs (with context) Find and Delete Files Older than 30 Days Get Directory Size Sorted Find Duplicate Files (by name) Search Multiple Extensions Find Large Log Files and Archive Them Count Total Files by Type Monitor Disk Usage Over Time Find and Remove Empty Directories Extract Unique IPs from Log File Count Lines in All Python Files Find Files Modified Today Generate File Size Report by Type Create Incremental Backup of Directory Find and List Permissions Issues Monitor Process Memory Usage Find Recently Modified Files (last 1 hour) Count Total Size by File Extension Quick Reference Card Notes

Trang này

Sunex 31/07/2026 · 23 phút đọc

Ngày tạo

31/07/2026

Cập nhật

Lượt xem

14

Đọc

23m

Linux/Ubuntu Commands - Tổng Hợp Toàn Diện

  • find . -type f -name “* *” | while read file; do mv “$file” “${file// /_}”; done Bao gồm:
  • Tìm kiếm files (find)
  • Kiểm tra số lượng files
  • Dung lượng files
  • Tìm text trong tài liệu (grep)
  • Quản lý files & directories
  • Quản lý users & permissions
  • Quản lý packages
  • Quản lý services
  • Networking
  • Disk & storage
  • Process management
  • Text processing
  • Compression
  • System info & monitoring

Table of Contents

  1. Tìm Kiếm Files (find)
  2. Đếm Số Lượng Files
  3. Kiểm Tra Dung Lượng Files
  4. Tìm Text trong Tài Liệu (grep)
  5. Quản lý Files & Directories
  6. Quản lý Users & Permissions
  7. Quản lý Packages (apt)
  8. Quản lý Services
  9. Networking
  10. Disk & Storage
  11. Process Management
  12. Text Processing
  13. Compression
  14. System Info & Monitoring
  15. Useful Shortcuts & Tips
  16. Advanced/Useful Commands
  17. Practical Examples

1. Tìm Kiếm Files (find)

Cơ bản

# Tìm theo tên
find /path -name "*.txt"              # Tìm file .txt
find /path -name "*.log" -type f      # Type f = file
find /path -type d -name "backup"     # Type d = directory
find . -name "*test*"                 # Wildcards

# Case insensitive
find /path -iname "*.TXT"             # Bỏ qua hoa/thường

# Tìm theo phần mở rộng
find . -name "*.{txt,log,md}"         # Multiple extensions
find . -name "*.js" -o -name "*.css"  # OR operator

Tìm theo thời gian

# Sửa đổi trong 7 ngày
find . -mtime -7                      # Last 7 days
find . -mtime 7                       # Exactly 7 days ago
find . -mtime +7                      # Older than 7 days

# Minutes
find . -mmin -30                      # Last 30 minutes
find . -mmin +30                      # Older than 30 minutes

# Truy cập
find . -atime -1                      # Accessed last 1 day
find . -ctime -1                      # Changed (metadata) last 1 day

# Date range
find . -newermt "2024-01-15" -not -newermt "2024-01-20"  # Between dates

Tìm theo kích thước

# Size
find . -size 100M                     # Exactly 100MB
find . -size +100M                    # Larger than 100MB
find . -size -100M                    # Smaller than 100MB
find . -size +1G -size -5G            # Between 1GB and 5GB

# Size units: c(bytes), k(KB), M(MB), G(GB)
find . -size +10k -size -100k         # 10KB to 100KB

Tìm theo user/permissions

# Owner
find . -user username                 # Files owned by user
find . -user username -type f         # Files only
find . -not -user root                # NOT owned by root

# Group
find . -group groupname

# Permissions
find . -perm 644                      # Exact permissions
find . -perm -644                     # At least these permissions
find . -perm /644                     # Any of these permissions
find . -perm /u+x                     # Has execute for owner
find . -perm /777                     # World-writable

Combinations (AND/OR)

# AND (mặc định)
find . -name "*.txt" -type f -size +1M    # .txt files, type f, > 1MB

# OR
find . -name "*.txt" -o -name "*.log"     # .txt OR .log

# NOT
find . -not -name "*.txt"                 # NOT .txt
find . -name "*.txt" ! -path "*/temp/*"   # NOT in temp dir

# Complex
find . -type f -name "*.log" -mtime +30 -size +10M
# Log files, older than 30 days, larger than 10MB

Action (-exec / -delete)

# Execute command
find . -name "*.tmp" -exec rm {} \;        # Delete files
find . -name "*.log" -exec cat {} \;       # Print content
find . -type f -exec chmod 644 {} \;       # Change permissions

# Better syntax (safe)
find . -name "*.tmp" -exec rm {} +         # + instead of \;
find . -name "*.bak" -delete               # Direct delete

# Print results
find . -name "*.txt" -print               # Default
find . -name "*.txt" -print0              # Null-terminated (safe for xargs)
find . -name "*.txt" -printf "%f\n"       # File name only
find . -name "*.txt" -printf "%s %p\n"    # Size + path

Example commands

# Tìm tất cả .log files trong 7 ngày, > 10MB
find /var/log -name "*.log" -mtime -7 -size +10M

# Tìm empty files
find . -type f -empty

# Tìm empty directories
find . -type d -empty

# Tìm files not accessed in 1 year
find . -atime +365

# Tìm symbolic links
find . -type l

# Tìm files với spaces trong tên
find . -name "* *"

# Tìm files và tính tổng size
find . -name "*.log" -type f -exec du -c {} + | tail -1

2. Đếm Số Lượng Files

Đơn giản

# Đếm files trong thư mục hiện tại
ls -1 | wc -l                         # Count entries
ls -1f | wc -l                        # Force no color

# Chỉ files (không count directories)
ls -1f -type f 2>/dev/null | wc -l

# Chỉ directories
ls -d */ | wc -l

# Count với pattern
ls -1 *.txt 2>/dev/null | wc -l      # Count .txt files
ls -1 *.{txt,log} 2>/dev/null | wc -l # .txt + .log

Dùng find

# Đếm tất cả files
find . -type f | wc -l

# Đếm files với pattern
find . -type f -name "*.txt" | wc -l

# Đếm files theo extension
find . -type f -name "*.log" | wc -l

# Đếm directories
find . -type d | wc -l

# Count by extension (report)
find . -type f | sed 's/.*\.//' | sort | uniq -c | sort -rn
# Output:
#    45 txt
#    23 log
#    12 json

# Đếm files theo folder
find . -maxdepth 1 -type d -exec sh -c 'echo -n "$1: "; find "$1" -type f | wc -l' _ {} \;
# Output:
# ./dir1: 25
# ./dir2: 40
# ./dir3: 15

Advanced counting

# Đếm files lớn hơn 100MB
find . -type f -size +100M | wc -l

# Đếm files sửa đổi trong 7 ngày
find . -type f -mtime -7 | wc -l

# Đếm files theo owner
find . -type f -user username | wc -l

# Đếm non-empty files
find . -type f -not -empty | wc -l

# Đếm empty files
find . -type f -empty | wc -l

3. Kiểm Tra Dung Lượng Files

Size của file/folder

# Một file
ls -lh file.txt                       # Human-readable size
ls -l file.txt                        # Bytes
stat file.txt                         # Detailed info

# Directory size
du -h /path/to/dir                    # Directory total size
du -sh /path/to/dir                   # Summary (single line)
du -h /path/to/dir | head -20         # Top 20 largest

# Recursively show sizes
du -ah /path/to/dir                   # All files + dirs
du -ah /path/to/dir | sort -rh | head -20  # Top 20

Disk usage overview

# Filesystem usage
df -h                                 # All mounted filesystems
df -h /home                           # Specific filesystem
df -i                                 # Inode usage

# Largest directories
du -sh /*                             # First-level directories
du -sh /* | sort -rh                  # Sorted by size
du -sh /* | sort -rh | head -10       # Top 10

# Recursive (show all levels)
du -h --max-depth=3 /path             # Max 3 levels deep
du -h --max-depth=2 /home | sort -rh | head -15

Find files by size

# Tất cả files > 100MB
find . -type f -size +100M -exec ls -lh {} \;

# Tất cả files > 1GB
find . -type f -size +1G

# 10MB - 100MB
find . -type f -size +10M -size -100M

# Tất cả files + size, sorted
find . -type f -exec ls -lhS {} \; | awk '{print $5, $9}'

# Files + size + path
find . -type f -printf '%s %p\n' | sort -rn | head -20
# Output: (bytes and path)
# 1073741824 ./largefile.iso
# 536870912 ./backup.tar.gz

Detailed size report

# Directory size breakdown
du -sh ./* | sort -rh

# Sample output:
# 5.2G    ./videos
# 2.1G    ./projects
# 1.8G    ./backups
# 256M    ./documents

# Size by file type
find . -type f | sed 's/.*\.//' | sort | uniq -c | while read count ext; do
  find . -type f -name "*.$ext" -exec du -c {} + | tail -1 | awk "{print \$1 \" \" \"$ext\"}"
done | sort -rn

# Output:
# 5368709120 mp4
# 2147483648 zip
# 1073741824 iso

4. Tìm Text trong Tài Liệu (grep)

Cơ bản

# Tìm text trong file
grep "pattern" file.txt               # Find text
grep -n "pattern" file.txt            # With line numbers
grep -i "pattern" file.txt            # Case insensitive
grep -w "word" file.txt               # Whole word only
grep -x "exact line" file.txt         # Exact line match

Tìm trong multiple files

# Tất cả files
grep -r "pattern" /path               # Recursive
grep -r "pattern" /path --include="*.txt"  # Specific extension
grep -r "pattern" /path --exclude="*.log"  # Exclude extension
grep -r "pattern" /path --exclude-dir=.git # Exclude directory

# Tìm file names only
grep -r "pattern" /path -l            # File names
grep -r "pattern" /path -L            # Files NOT containing pattern

# Count occurrences
grep -r "pattern" /path -c            # Count per file
grep "pattern" file.txt | wc -l       # Total count

Context lines

# Show context
grep -A 3 "pattern" file.txt          # 3 lines after
grep -B 3 "pattern" file.txt          # 3 lines before
grep -C 3 "pattern" file.txt          # 3 lines before + after

# Example:
# grep -B 2 -A 2 "error" system.log
# Shows 2 lines before and after "error"

Regular expressions

# Basic regex
grep "^error" file.txt                # Start with "error"
grep "error$" file.txt                # End with "error"
grep "^$" file.txt                    # Empty lines
grep -v "^#" file.txt                 # Skip comments

# Extended regex (-E or egrep)
grep -E "error|warning" file.txt      # OR
grep -E "^(error|ERROR)" file.txt     # OR at start
grep -E "[0-9]{3}-[0-9]{4}" file.txt  # Phone number pattern

# Character class
grep "[0-9]" file.txt                 # Contains digits
grep "[a-z]" file.txt                 # Lowercase letters
grep "^[^#]" file.txt                 # NOT starting with #

Useful flags

# Invert match (NOT)
grep -v "pattern" file.txt            # Lines NOT matching
grep -v "^#" config.txt               # Skip comments

# Color output
grep --color "pattern" file.txt       # Highlight matches
grep --color=always "pattern" file.txt

# Quiet mode
grep -q "pattern" file.txt            # No output (just return code)
if grep -q "error" log.txt; then echo "Found"; fi

# Binary files
grep -I "pattern" file                # Skip binary files
grep -a "pattern" file.bin            # Treat binary as text

# Word boundary
grep "\bword\b" file.txt              # Word boundaries
grep -w "word" file.txt               # Same (-w flag)

Pipe with other commands

# Count lines matching
grep "pattern" file.txt | wc -l

# Get unique matches
grep "pattern" file.txt | sort -u

# Sort matches
grep "error" log.txt | sort

# Extract specific field
grep "error" log.txt | cut -d' ' -f1,2

# Find + grep
find . -name "*.log" -type f -exec grep "ERROR" {} +

# Pipeline example
grep "2024-01" access.log | grep "GET" | cut -d' ' -f1 | sort | uniq -c
# Extract IPs from Jan 2024 GET requests, count by IP

5. Quản lý Files & Directories

Liệt kê files

# Liệt kê files
ls                          # Danh sách file đơn giản
ls -la                      # Chi tiết + hidden files
ls -lh                      # Size dễ đọc (KB, MB, GB)
ls -lt                      # Sắp xếp theo thời gian sửa
ls -lS                      # Sắp xếp theo kích thước

Thay đổi thư mục

# Thay đổi thư mục
cd /path/to/dir             # Vào thư mục
cd ~                        # Vào home
cd -                        # Quay lại thư mục trước
pwd                         # In đường dẫn hiện tại

Tạo/Xóa

# Tạo
mkdir my_dir                # Tạo thư mục
mkdir -p a/b/c              # Tạo nested directories
rmdir empty_dir             # Xóa thư mục rỗng
rm file.txt                 # Xóa file
rm -r directory/            # Xóa thư mục + nội dung
rm -f file.txt              # Force delete (bỏ qua warning)

Copy/Move

# Copy
cp file1.txt file2.txt      # Copy file
cp -r dir1/ dir2/           # Copy thư mục
mv file1.txt file2.txt      # Rename/move file
mv dir1/ dir2/              # Move thư mục

Xem nội dung

# Xem nội dung
cat file.txt                # Hiển thị toàn bộ file
cat file1.txt file2.txt     # Nối 2 files
head -n 20 file.txt         # 20 dòng đầu
tail -n 20 file.txt         # 20 dòng cuối
tail -f file.txt            # Real-time (logs)
less file.txt               # Viewer interactif (space/q)
more file.txt               # Viewer đơn giản
wc -l file.txt              # Đếm số dòng

6. Quản lý Users & Permissions

User info

# User info
whoami                      # User hiện tại
id                          # UID/GID
sudo su                     # Thành root
su - username               # Switch user

Tạo/Xóa user

# Tạo/Xóa user
sudo useradd username       # Tạo user
sudo userdel username       # Xóa user
sudo passwd username        # Đổi password
sudo usermod -aG sudo username  # Thêm vào sudo group

Permissions (rwx)

# Permissions
chmod 755 file.txt          # Owner: rwx, Others: r-x
chmod 644 file.txt          # Owner: rw-, Others: r--
chmod +x script.sh          # Thêm execute permission
chmod -r directory/         # Recursive
chown user:group file.txt   # Đổi owner
chown -r user:group dir/    # Recursive

sudo (SuperUser DO)

# sudo
sudo command                # Chạy command với root
sudo !!                     # Chạy lại command trước với sudo
sudo -l                     # List sudo permissions

7. Quản lý Packages (apt)

Update/Upgrade

# Update/Upgrade
sudo apt update             # Cập nhật package list
sudo apt upgrade            # Upgrade packages
sudo apt full-upgrade       # Upgrade + remove old packages
sudo apt autoremove         # Xóa unused packages

Install/Remove

# Install/Remove
sudo apt install package    # Cài package
sudo apt install pkg1 pkg2  # Cài nhiều packages
sudo apt remove package     # Xóa package (giữ config)
sudo apt purge package      # Xóa package + config
sudo apt search keyword     # Tìm package
apt show package            # Chi tiết package
apt list --installed        # List installed packages

Repository

# Repository
sudo add-apt-repository ppa:name/ppa  # Thêm PPA
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys KEY_ID

8. Quản lý Services

Systemctl (systemd)

# Systemctl
sudo systemctl start service    # Khởi động service
sudo systemctl stop service     # Dừng service
sudo systemctl restart service  # Restart service
sudo systemctl status service   # Status service
sudo systemctl enable service   # Auto-start on boot
sudo systemctl disable service  # Disable auto-start
systemctl list-units --type=service  # List all services

Service logs

# Logs
sudo journalctl -u service_name     # Service logs
sudo journalctl -u service -f       # Real-time logs
sudo journalctl --since "2024-01-15"  # Logs từ ngày

9. Networking

IP/Network info

# IP/Network info
ip addr                     # IP addresses
ip link show                # Network interfaces
hostname                    # Machine hostname
sudo hostname newhostname   # Đổi hostname
ifconfig                    # Network config (deprecated)

Ping/Trace

# Ping/Trace
ping google.com             # Test connectivity
ping -c 5 google.com        # 5 packets
traceroute google.com       # Trace route
mtr google.com              # Real-time traceroute

Port/Service

# Port/Service
netstat -tlnp               # Listen ports + PID
ss -tlnp                    # Same (modern)
ss -tln                     # List TCP ports
lsof -i :8080               # Process on port 8080
nc -zv localhost 8080       # Check port open

DNS

# DNS
nslookup google.com         # DNS lookup
dig google.com              # Detailed DNS query
cat /etc/resolv.conf        # DNS config
cat /etc/hosts              # Local hostname mapping

SSH

# SSH
ssh user@host               # SSH login
ssh -p 2222 user@host       # Port custom
ssh-keygen -t rsa -b 4096   # Gen SSH key
ssh-copy-id user@host       # Copy key to server
scp file.txt user@host:/path # Copy file via SSH
scp -r dir/ user@host:/path # Copy directory

10. Disk & Storage

Disk usage

# Disk usage
df -h                       # Disk space (human-readable)
du -h /path                 # Directory size
du -sh /path                # Total directory size
du -sh /* | sort -h         # Largest directories
tree /path                  # Tree structure

Mount/Unmount

# Mount/Unmount
mount                       # List mounted filesystems
sudo mount /dev/sda1 /mnt/usb  # Mount device
sudo umount /mnt/usb        # Unmount
lsblk                       # Block devices
blkid                       # Device UUIDs

Disk check

# Disk check
sudo fsck /dev/sda1         # Check filesystem (unmount first!)

11. Process Management

List processes

# List processes
ps aux                      # All processes
ps aux | grep process_name  # Find process
top                         # Real-time processes (interactive)
htop                        # Better top (install: apt install htop)
pgrep process_name          # Get PID

Kill process

# Kill process
kill PID                    # Graceful kill
kill -9 PID                 # Force kill
killall process_name        # Kill by name
pkill process_name          # Same

Background/Foreground

# Background/Foreground
command &                   # Run in background
Ctrl+Z                      # Suspend foreground
bg                          # Resume in background
fg                          # Bring to foreground
jobs                        # List jobs
nohup command &             # Run persistent (ignore hangup)

12. Text Processing

Search & Replace

# Search & Replace
sed 's/old/new/' file.txt           # Replace first
sed 's/old/new/g' file.txt          # Replace all
sed -i 's/old/new/g' file.txt       # In-place edit
sed -n '5,10p' file.txt             # Print lines 5-10

Grep variants

# Grep variants
grep -v pattern file.txt            # Invert match
grep -c pattern file.txt            # Count matches
grep -o pattern file.txt            # Only matches
grep -A 3 pattern file.txt          # 3 lines after
grep -B 3 pattern file.txt          # 3 lines before

Sorting/Unique

# Sorting/Unique
sort file.txt                       # Sort lines
sort -n file.txt                    # Numeric sort
sort -rn file.txt                   # Reverse numeric
uniq file.txt                       # Remove duplicates (needs sorted)
sort file.txt | uniq -c             # Count duplicates

Cut/Awk/Paste

# Cut/Awk/Paste
cut -d',' -f1,3 file.csv            # Extract columns
awk '{print $1, $3}' file.txt       # Print columns
awk -F',' '{print $2}' file.csv     # Custom delimiter
paste file1.txt file2.txt           # Merge files

Other

# Other
tr 'a-z' 'A-Z' < file.txt          # Translate (lowercase → uppercase)
rev file.txt                        # Reverse lines
tee output.txt                      # Save stdin + stdout
xargs command                       # Pass stdin as arguments

13. Compression

Tar (archive)

# Tar (archive)
tar -czf archive.tar.gz dir/        # Compress directory
tar -xzf archive.tar.gz             # Extract .tar.gz
tar -cf archive.tar dir/            # Create tar (no compress)
tar -tf archive.tar.gz              # List contents

Zip

# Zip
zip -r archive.zip dir/             # Zip directory
unzip archive.zip                   # Unzip
unzip -l archive.zip                # List contents

Gzip

# Gzip
gzip file.txt                       # Compress (file.txt.gz)
gunzip file.txt.gz                  # Decompress
gzip -d file.txt.gz                 # Same

Individual file compression

# Individual file compression
bzip2 file.txt                      # Compress .bz2
xz file.txt                         # Compress .xz

14. System Info & Monitoring

System info

# System info
uname -a                    # Kernel info
cat /etc/os-release         # OS version
lsb_release -a              # Ubuntu version
uptime                      # System uptime
free -h                     # Memory usage
vmstat 1 5                  # Virtual memory (5 samples, 1sec interval)
iostat -x 1 5               # Disk I/O

CPU info

# CPU info
nproc                       # Number of CPUs
lscpu                       # CPU details
cat /proc/cpuinfo           # Detailed CPU

Temperature

# Temperature
sensors                     # CPU temperature (install: apt install lm-sensors)
watch -n 1 sensors          # Real-time temp

Logs

# Logs
dmesg                       # Kernel messages
dmesg | tail -20            # Last 20 kernel messages
cat /var/log/syslog         # System log
tail -f /var/log/auth.log   # Auth log (real-time)

15. Useful Shortcuts & Tips

History

# History
history                     # Show command history
history | grep keyword      # Search history
!!                          # Repeat last command
!5                          # Repeat command #5
Ctrl+R                      # Search history (reverse-i-search)

Aliases (thêm vào ~/.bashrc hoặc ~/.zshrc)

# Aliases
alias ll='ls -lah'
alias gs='git status'
alias dc='docker-compose'

Quick commands

# Quick commands
which command               # Location of command
whatis command              # Short description
man command                 # Manual (press q to quit)
command --help              # Help info
command -h                  # Quick help

Piping & Redirection

# Piping & Redirection
command > file.txt          # Output to file (overwrite)
command >> file.txt         # Output to file (append)
command 2> error.log        # Redirect stderr
command &> file.txt         # Redirect stdout + stderr
cmd1 | cmd2                 # Pipe output

Variables

# Variables
echo $HOME                  # Home directory
echo $USER                  # Current user
echo $PATH                  # System PATH
env                         # All environment variables
export VAR=value            # Set environment variable

16. Advanced/Useful Commands

System updates

# System updates
sudo apt update && sudo apt upgrade -y   # One-liner

Create file

# Create file
touch file.txt              # Create empty file
echo "content" > file.txt   # Create with content

Download

# Download
wget https://example.com/file.zip   # Download
curl -O https://example.com/file    # Download
curl -I https://example.com         # Headers only

Cron (scheduled tasks)

# Cron (scheduled tasks)
crontab -e                  # Edit cron jobs
crontab -l                  # List cron jobs
# Format: minute hour day month day_of_week command
# 0 2 * * * /path/to/script.sh    # Daily at 2:00 AM

Watch command changes

# Watch command changes
watch -n 2 'ps aux | grep process'  # Refresh every 2 sec

Benchmark

# Benchmark
time command                # Measure execution time
stress-ng --cpu 4 --timeout 10s  # CPU stress test (install: apt install stress-ng)

File size

# File size
stat file.txt               # File details
ls -lah file.txt            # File with size

17. Practical Examples

Find & Count Files > 100MB

find /home -type f -size +100M | wc -l
# Output: 15 files larger than 100MB

List 10 Largest Files

find . -type f -exec ls -lhS {} + | head -20 | awk '{print $5, $9}'
# Or:
find . -type f -printf '%s %p\n' | sort -rn | head -10 | awk '{print $1/1024/1024 "MB", $2}'

Find All .log Files, > 1MB, Modified in Last 7 Days

find /var/log -name "*.log" -type f -size +1M -mtime -7 -exec ls -lh {} \;

Count Files by Extension

find . -type f | sed 's/.*\.//' | sort | uniq -c | sort -rn

Find Text in All Config Files

grep -r "database" /etc --include="*.conf" --include="*.cfg"

Find Errors in Logs (with context)

grep -B 2 -A 2 "ERROR" /var/log/app.log | head -50

Find and Delete Files Older than 30 Days

find /tmp -type f -mtime +30 -delete
# Or with confirmation:
find /tmp -type f -mtime +30 -exec rm -i {} \;

Get Directory Size Sorted

du -sh /home/* | sort -rh

Find Duplicate Files (by name)

find . -type f -name "*" | sed 's/.*\///' | sort | uniq -d

Search Multiple Extensions

find . -type f \( -name "*.txt" -o -name "*.log" -o -name "*.md" \)

Find Large Log Files and Archive Them

find /var/log -name "*.log" -type f -size +100M -exec tar -czf {}.tar.gz {} \;

Count Total Files by Type

find . -type f | sed 's/.*\.//' | sort | uniq -c
# Output:
#  123 txt
#   45 log
#   12 json

Monitor Disk Usage Over Time

while true; do clear; du -sh /home/* | sort -rh; sleep 10; done

Find and Remove Empty Directories

find . -type d -empty -delete

Extract Unique IPs from Log File

grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' access.log | sort -u

Count Lines in All Python Files

find . -name "*.py" -exec wc -l {} + | tail -1

Find Files Modified Today

find . -type f -mtime 0

Generate File Size Report by Type

find . -type f | awk -F. '{print $NF}' | sort | uniq | while read ext; do
  echo -n "$ext: "
  find . -name "*.$ext" -type f -exec du -c {} + | tail -1 | awk '{print $1}'
done

Create Incremental Backup of Directory

tar -czf backup_$(date +%Y%m%d_%H%M%S).tar.gz /path/to/dir

Find and List Permissions Issues

find . -type f ! -perm 644 -o -type d ! -perm 755

Monitor Process Memory Usage

watch -n 1 'ps aux --sort=-%mem | head -15'

Find Recently Modified Files (last 1 hour)

find . -type f -mmin -60

Count Total Size by File Extension

find . -type f -printf '%s %p\n' | awk '{ext=substr($NF,index($NF,".")); sum[ext]+=$1} 
END {for (e in sum) printf "%s: %d bytes\n", e, sum[e]}' | sort -t: -k2 -rn

Quick Reference Card

CategorySyntaxExample
Find Filesfind /path -name "pattern"find . -name "*.txt"
Find by Sizefind . -size +100Mfind . -size +1G -size -5G
Find by Timefind . -mtime -7find . -mtime -7 -size +10M
Count Filesfind . -type f \| wc -lfind . -name "*.txt" \| wc -l
Directory Sizedu -sh /pathdu -sh /home/*
Search Textgrep "pattern" filegrep -r "text" /path
Count Matchesgrep "pattern" file \| wc -lgrep -c "error" log.txt
Replace Textsed 's/old/new/g' filesed -i 's/old/new/g' file.txt
List Processesps aux \| grep nameps aux \| grep apache
Kill Processkill -9 PIDkillall apache2

Notes

  • Các flag thường dùng:

    • -r / --recursive: Recursive (áp dụng cho tất cả subdirectories)
    • -f / --force: Force (bỏ qua warning)
    • -i / --interactive: Interactive (hỏi xác nhận)
    • -h / --human-readable: Human-readable (KB, MB, GB)
    • -n / --number: Line number
    • -v / --invert-match: Invert match (NOT)
  • Safe practices:

    • Luôn preview trước khi delete: find . -name "*.tmp" -type f trước find . -name "*.tmp" -delete
    • Dùng -exec rm -i {} thay vì -delete để hỏi xác nhận
    • Backup quan trọng trước khi thực hiện mass operations
  • Performance tips:

    • Dùng find thay vì ls cho tìm kiếm lớn
    • Dùng -print0 với xargs -0 cho tên files có spaces
    • Limit depth với --max-depth để tránh quét sâu quá

Created: 2024 Version: 1.0

Contact
Facebook
TOP