ค้นหาคำที่ต้องการในทุกๆ ไฟล์ด้วยคำสั่ง grep

RSS Feed

ช่วงนี้งานเข้าเยอะมาก พอดีมีงานนึงที่ต้องไล่โค้ดจากเว็บเก่าที่เขียนได้เละมากๆ ไม่มีโครงสร้าง และมีไฟล์อยู่มั่วเต็มไปหมด ปรากฎว่าเราต้องการดูคลาสตัวนึงจากในบรรดาเป็นร้อยๆ ไฟล์จะทำอย่างไร?

ให้เราเปิด Terminal แล้ว cd ไปที่โฟลเดอร์ที่ต้องการหาไฟล์ แล้วพิมพ์คำสั่ง (สมมติว่าชื่อคลาสที่ต้องการค้นหามีชื่อว่า MyClass)

grep "MyClass" *

คำสั่งข้างบนจะค้นหาแค่ทุกๆ ไฟล์จากในไดเร็กทอรี่ปัจจุบันเท่านั้น แต่จะไม่ค้นหาในไดเร็กทอรี่ย่อยๆ ลงไป แต่ถ้าต้องการเพิ่มเงื่อนไขเป็น ค้นหาในทุกๆ ไดเร็กทอรี่ย่อยด้วย และค้นหาเฉพาะไฟล์ .php ให้พิมพ์คำสั่ง

grep -R "MyClass" *.php

ขอตัวไปปั่นงานต่อก่อนล่ะครับ

Update: จากคอมเมนท์ของ hiddenmin ถ้าเราเพิ่ม -n จะทำให้เห็นว่าข้อความที่เราค้นหาอยู่บรรทัดไหนด้วยนะครับ

grep -Rn "MyClass" *.php

-n ด้วยก็ดีนะเธอ

จะได้รู้ว่าอยู่บันทัดใหน

 

ต้องเธอว์ด้วยสิเธอว์ ไม่อินเทรนด์เลย :P

ปล. เพิ่มให้แล้วนะเธอว์

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.
  • Allowed HTML tags: <a> <br> <cite> <code> <dd> <div> <dl> <dt> <em> <img> <li> <ol> <p> <span> <strong> <ul>
    Allowed Style properties: color, font, font-family, font-size, font-style, font-weight, text-align
  • You can enable syntax highlighting of source code with the following tags: <blockquote>, <code>, <pre>, <apache>, <bash>, <c>, <cpp>, <css>, <drupal5>, <drupal6>, <html>, <java>, <javascript>, <mysql>, <php>, <python>, <ruby>, <smarty>. The supported tag styles are: <foo>, [foo].
  • Image links with 'rel="lightbox"' in the <a> tag will appear in a Lightbox when clicked on.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.