Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> สมาร์ทโฟน >> Linux

เริ่มต้นใช้งานคำสั่ง grep

คู่มือสั้นนี้จะทำให้คุณเริ่มใช้คำสั่ง grep ที่มีประโยชน์มาก สำหรับ Linux และ *nix OS อื่นๆ — รวมถึง macOS ล่าสุดได้ทันที

สำหรับผู้คุ้นเคยกับ Command Line Interface ของ Linux หรือ UNIX ค่อนข้างน่าจะเคยเจอ grep มาบ้าง grep เป็นเครื่องมือ Command Line ที่เยี่ยม ช่วยค้นหาคำหรือกลุ่มคำผ่านไฟล์ มาพร้อมกับเกือบทุก Flavor ของ Linux โดยค่าเริ่มต้น สำหรับผู้ไม่คุ้นเคยกับ grep นี่คือ Primer สั้นๆ

# grep www /etc/httpd/conf/httpd.conf

#ServerName www.example.com:80
DocumentRoot "/var/www/html"
# e.g., www.apache.org (on) or 204.62.129.132 (off).
Alias /icons/ "/var/www/icons/"

ในตัวอย่างข้างต้น เราใช้ grep ค้นหาคำว่า www ในไฟล์ /etc/httpd/conf/httpd.conf ได้ผลลัพธ์ 4 บรรทัด คำสั่งนี้ตรงไปตรงมา grep มาพร้อมฟังก์ชันเพิ่มเติมมาก ใครสนใจ manpage ของ grep ให้รัน man grep

ตอนนี้มาดูฟีเจอร์ของ grep ที่อนุญาตให้ค้นหา 2 คำในเอกสารด้วยคำสั่งเดียว ลองปรับคำสั่งข้างต้นให้ค้นหา www และ server พร้อมกัน

# grep 'www\|server' /etc/httpd/conf/httpd.conf

# SetHandler server-status
# Allow remote server configuration reports, with the URL of
# https://servername/server-info (requires that mod_info.c be loaded).
#ServerName www.example.com:80
DocumentRoot "/var/www/html"
# e.g., www.apache.org (on) or 204.62.129.132 (off).
Alias /icons/ "/var/www/icons/"
# SetHandler server-info
# enable the proxy server:
# ("Full" adds the server version; "Block" removes all outgoing Via: headers)
# use only name-based virtual hosts so the server doesn't need to worry about
# server name.

ดูได้ว่า Output มากกว่าคำสั่งแรก (คืน 12 บรรทัด) สังเกตการเปลี่ยนแปลงคำค้นหาเป็น 'www\|server' จำได้ไหม ต้องใช้ Forward Slash ( \ ) ก่อน Pipe ( | ) มิฉะนั้นจะไม่ได้ผลลัพธ์เดียวกัน สามารถใช้เครื่องมือ egrep เพื่อรันการค้นหาแบบเดียวกันโดยไม่ต้องใช้ Forward Slash ลองดู:

# egrep 'www|server' /etc/httpd/conf/httpd.conf

# SetHandler server-status
# Allow remote server configuration reports, with the URL of
# https://servername/server-info (requires that mod_info.c be loaded).
#ServerName www.example.com:80
DocumentRoot "/var/www/html"
# e.g., www.apache.org (on) or 204.62.129.132 (off).
Alias /icons/ "/var/www/icons/"
# SetHandler server-info
# enable the proxy server:
# ("Full" adds the server version; "Block" removes all outgoing Via: headers)
# use only name-based virtual hosts so the server doesn't need to worry about
# server name.

คุณยังสามารถเพิ่ม Pipe อีกตัว และค้นหาคำที่สามได้ คำสั่งจะเป็น # egrep 'www|server|apache' /etc/httpd/conf/httpd.conf

เมื่อรวมคำสั่ง grep กับ find เข้าด้วยกัน จะไม่มีอะไรมากที่คุณหาไม่เจอบนคอมพิวเตอร์ของคุณ :)