Hướng dẫn ngắn này giúp bạn bắt đầu dùng lệnh "grep" cực hữu ích cho Linux và các *nix khác – kể cả macOS mới nhất.
Với bất kỳ ai quen giao diện dòng lệnh Linux/UNIX, rất có thể grep đã lướt qua đường. grep là công cụ dòng lệnh tuyệt vời giúp tìm từ hoặc cụm từ qua file. Nó đi kèm hầu như mọi phiên bản Linux mặc định. Cho những không quen grep, đây là tóm tắt nhanh.
# 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/”
Trong ví dụ trên dùng grep tìm từ www trong file /etc/httpd/conf/httpd.conf. 4 kết quả trả về. Lệnh khá đơn giản. grep đi kèm nhiều chức năng hơn. Tự do xem trang man grep bằng man grep.
Bây giờ xem tính năng grep tìm hai từ trong tài liệu, chỉ một lệnh. Sửa lệnh trên tìm www và 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.
Như thấy đầu ra lớn hơn lệnh thứ hai (12 dòng). Chú ý cách sửa lệnh: từ tìm thành ‘www\|server’. Nhớ dùng dấu gạch chéo ngược ( \ ) trước dấu pipe ( | ), không thì kết quả khác. Thay vào đó bạn dùng egrep chạy tìm tương tự không cần gạch chéo. Thử:
# 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.
Bạn cũng thêm pipe khác tìm từ thứ ba. Lệnh thành # egrep ‘www|server|apache’ /etc/httpd/conf/httpd.conf.
Khi kết hợp grep với find, không có gì bạn không tìm thấy trên máy :)