Thuta Learning
ရှာဖွေရန်
IntermediateDevOps & Toolsbeginner

grep နဲ့ စာသား ရှာဖွေခြင်း

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • grep နဲ့ စာသား ရှာဖွေခြင်း ကို ကြောက်စရာမလိုအောင် နားလည်မယ်
  • Terminal ထဲမှာ ကိုယ်တိုင် command ကို စမ်းသုံးတတ်အောင် လုပ်မယ်
  • Real server/project မှာ ဒီ command ဘယ်လို အသုံးဝင်သလဲ ချိတ်မြင်မယ်

ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်

grep pattern file က file ထဲမှာ pattern ပါတဲ့ line တွေကို ရှာဖမ်းပြပါတယ် (grep = 'global regular expression print'၊ နာမည်ကတော့ ရှုပ်ပေမယ့် သုံးရတာက ရိုးရှင်းပါတယ်)။ -i flag က case-insensitive (အကြီးအသေး မခွဲ) ရှာစေပါတယ်။ -r flag က folder တစ်ခုလုံးထဲ (sub-folder အားလုံးအပါအဝင်) ရှာစေပါတယ်။ -n flag က line number ပါတွဲပြပါတယ် — ဖိုင်ကြီးထဲမှာ error ဘယ် line မှာလဲ ချက်ချင်းသိစေပါတယ်။ -v flag ကတော့ ဆန့်ကျင်ဘက် — pattern မပါတဲ့ line ကိုပဲ ပြပါတယ်။

လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်

Log ဖိုင်ကြီးတစ်ခုထဲက error line ပဲ ကြည့်ချင်ရင် grep -n "ERROR" app.log လို့ ရိုက်ပါ။ Project folder တစ်ခုလုံးထဲမှာ TODO comment ဘယ်ဖိုင်တွေမှာ ကျန်နေလဲ ရှာချင်ရင် grep -rn "TODO" . က folder အားလုံး scan လုပ်ပြီး file name + line number တွဲပြပေးပါတယ် — code review လုပ်တဲ့အခါ အသုံးအများဆုံး command တစ်ခုပါ။ pipe (ယခင်အခန်း) နဲ့ ပေါင်းသုံးရင် ps aux | grep nginx လိုမျိုး process ရှာတဲ့ workflow ထဲမှာလည်း grep က အခန်းကဏ္ဍ ကြီးမားပါတယ်။

အတူတူ terminal ထဲ စမ်းမယ်

bash
grep "ERROR" app.log
grep -in "error" app.log
grep -rn "TODO" .
grep -v "DEBUG" app.log > errors-only.log
You should see
'ERROR' ပါတဲ့ line များကို line number တွဲပြီး terminal ပေါ်တွင် ပေါ်လာမည်။

၅ မိနစ် စမ်းကြည့်

notes.txt ဖိုင်တစ်ခုထဲမှာ line ၅ ကြောင်း ရေးပါ (တစ်ကြောင်းမှာ TODO ထည့်ပါ)။ grep -n TODO notes.txt နဲ့ ရှာကြည့်ပါ။

သတိလေးတစ်ချက်

grep ရဲ့ pattern ထဲ special character (.、*、[ စသည်) ပါရင် regex အဖြစ် အလိုလို အနက်ကောက်နိုင်ပါတယ် — literal dot ရှာချင်ရင် grep -F (fixed string) သုံးလို့ရပါတယ်။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • grep pattern ကို quote မထားလို့ space ပါတဲ့ phrase ရှာရင် error ဖြစ်ခြင်း — quote ("phrase here") ထဲထားရပါမည်
  • -r ကို folder အစား ဖိုင်တစ်ခုတည်းပေါ်မှာ လိုအပ်တယ်ထင်ခြင်း (ဖိုင်တစ်ခုတည်းအတွက် -r မလို)

အခု ကိုယ်တိုင် စမ်းကြည့်

notes.txt ဖိုင်တစ်ခုထဲမှာ line ၅ ကြောင်း ရေးပါ (တစ်ကြောင်းမှာ TODO ထည့်ပါ)။ grep -n TODO notes.txt နဲ့ ရှာကြည့်ပါ။

You'll know it worked when: 'ERROR' ပါတဲ့ line များကို line number တွဲပြီး terminal ပေါ်တွင် ပေါ်လာမည်။

grep နဲ့ စာသား ရှာဖွေခြင်း | Thuta Learning