กลับไปหน้าสูตร
#rg#ripgrep#search#terminal#cheatsheet

RG Command Cheatsheet

รวมคำสั่ง rg (ripgrep) ที่ใช้บ่อยจริง: ค้นหาโค้ด, จำกัดไฟล์, ดู context, รวม hidden files และ one-liners ที่หยิบไปใช้ได้ทันที

29 มีนาคม 2569อ่านประมาณ 2 นาที

Find Only Certain Files

Commandใช้ทำอะไร
rg "useState" -t jsค้นหาเฉพาะไฟล์ JavaScript
rg "interface User" -t tsค้นหาเฉพาะไฟล์ TypeScript
rg "bg-red-500" app -g "*.tsx"ค้นหาเฉพาะไฟล์ที่ match glob
rg "axios" -g "*.ts" -g "*.tsx"ค้นหาหลาย pattern ไฟล์
rg "console.log" -g '!node_modules'ตัดโฟลเดอร์ที่ไม่อยากค้น
rg "TODO" src testsค้นหาเฉพาะหลายโฟลเดอร์

Output Control

Commandใช้ทำอะไร
rg -l "TODO"แสดงเฉพาะชื่อไฟล์ที่ match
rg -c "TODO"นับจำนวน match ต่อไฟล์
rg --count-matches "TODO"นับจำนวน match ทั้งจริงในแต่ละไฟล์
rg -o "https?://\S+" notes.mdแสดงเฉพาะส่วนที่ match
rg --filesแสดงรายการไฟล์ทั้งหมดที่ rg มองเห็น
`rg --filesrg "cheatsheet"`

Context Around Match

Commandใช้ทำอะไร
rg -C 2 "throw new Error"แสดงก่อนและหลัง 2 บรรทัด
rg -A 3 "if \(error\)"แสดง 3 บรรทัดหลัง match
rg -B 3 "return res"แสดง 3 บรรทัดก่อน match
rg --heading "TODO" srcแยกผลลัพธ์เป็นหัวข้อไฟล์ให้อ่านง่าย
rg --no-heading -n "TODO"output แบบเรียบ เหมาะกับ pipe ต่อ

Hidden And Ignored Files

Commandใช้ทำอะไร
rg "API_KEY" --hiddenรวมไฟล์ hidden เช่น .env.example
rg "TODO" -g '!.next' --hiddenรวม hidden แต่ตัดบางโฟลเดอร์ออก
rg "debug" -uuค้นหารวม ignored และ hidden
rg "debug" -uuuค้นหาแบบไม่แคร์ ignore, hidden, binary มากขึ้น

Regex That Is Often Useful

Commandใช้ทำอะไร
rg "^import .*react" srcหา line ที่ขึ้นต้นด้วย import
`rg "(GETPOST
rg "[0-9]{4}-[0-9]{2}-[0-9]{2}"หา pattern วันที่
`rg "\bFIXME\b\bTODO\b"`

Daily One-liners

# หา TODO ทั้งโปรเจกต์แบบอ่านง่าย
rg -n --heading "TODO|FIXME"

# หาไฟล์ที่ยังมี console.log
rg -l "console\.log"

# หา env vars ที่น่าจะ hardcode อยู่ใน source
rg -n --hidden "(API_KEY|SECRET|TOKEN|PASSWORD)" src

# หา endpoint ทั้งหมดในโปรเจกต์
rg -n "(/api/|https?://)" app src lib

# หาเฉพาะไฟล์ ts/tsx ที่ใช้ axios
rg -l "axios" -g "*.ts" -g "*.tsx"

# หา import ของ package ใด package หนึ่ง
rg -n "from ['\"]zod['\"]|require\(['\"]zod['\"]\)" src

# หาไฟล์ชื่อคล้าย config ด้วย rg
rg --files | rg "config|env|settings"

Quick Notes

เรื่องที่ควรรู้รายละเอียด
เร็วกว่า grep -R มากในโปรเจกต์ใหญ่เหมาะกับ codebase search ทุกวัน
respect .gitignore โดย defaultถ้าไม่เจอไฟล์ที่คิดว่าควรเจอ ให้ลอง --hidden หรือ -uu
ถ้าค้นหา string ตรง ๆใช้ -F จะตรงและปลอดภัยกว่า regex
ถ้าจะ pipe ต่อเข้า tool อื่นใช้ --no-heading -n อ่านง่ายกว่า

สูตรอื่นๆ

สูตรก่อนหน้า

rsync Command Cheatsheet

ไม่มีสูตรถัดไป