a magnifying glass searching through text

Cách tìm tệp trong Linux: Nắm vững các lệnh Tìm và Grep

Trong bài viết này, bạn sẽ tìm hiểu cách tìm tệp trong Linux bằng các công cụ khác nhau.

The “find” command cheatsheet

Tìm kiếm theo tên tập tin

“Find” is one of the most popular tools to search files in Linux. When you know the file name you can search for it using command below. Replace “/home” with a folder to search through and “filename.txt” with the file name.

$ find /home -name filename.txt

To search the current folder for a file replace “/home” with a dot (.) symbol:

$ find . -name Documents.zip
./Documents.zip

When you do not know the exact file name use the regular expression to look for a match. The asterisk (*) symbol matches any character set after the “Documents” keyword.

$ find /home -name "Documents*"
/home/eugene/Documents.zip
/home/eugene/Documents
/home/eugene/Phone/Documents

Tìm kiếm theo ngày sửa đổi

To search for files that were modified today add “-mtime” key to the find command:

$ find /home -mtime 0

Ví dụ: hãy tìm những bức ảnh đã được sửa đổi 10 ngày trước:

$ find Pictures/ -mtime 10
Pictures/Screenshots/Screenshot from 2023-11-03 10-29-49.png

Tìm kiếm theo loại tập tin

The “find” command in Linux allows you to search for files based on their type. Here are some examples:

Tìm kiếm thư mục: Để tìm tất cả các thư mục trong một đường dẫn cụ thể, hãy sử dụng tùy chọn -type d.

$ find /home -type d

Tìm kiếm tập tin thông thường: Ngược lại, để định vị các tệp thông thường, hãy sử dụng tùy chọn -type f.

$ find /home -type f -name "*.txt"

Tìm kiếm các liên kết tượng trưng: Để tìm kiếm các liên kết tượng trưng, ​​hãy sử dụng tùy chọn -type l.

$ find /home -type l -name "linkname"

Tìm kiếm phần mở rộng tệp cụ thể: Thu hẹp tìm kiếm của bạn bằng cách chỉ định phần mở rộng tệp.

$ find /home -type f -name "*.jpg"

Tiêu chí kết hợp

You can combine multiple criteria to make your searches more precise. Here’s an example:

Tìm kiếm các tệp đã sửa đổi có phần mở rộng cụ thể: Find files modified in the last 7 days with the extension “.log”.

$ find /var/logs -type f -name "*.log" -mtime -7

Tìm kiếm các tệp được sửa đổi giữa một phạm vi ngày: Xác định vị trí các tệp được sửa đổi trong khoảng thời gian từ ngày 1 tháng 11 năm 2023 đến ngày 5 tháng 11 năm 2023.

$ find /home -newermt 2023-11-01 ! -newermt 2023-11-06

Additional “find” Command Options

Bỏ qua phân biệt chữ hoa chữ thường: Nếu bạn muốn tìm kiếm không phân biệt chữ hoa chữ thường, hãy sử dụng tùy chọn -iname.

$ find /home -iname "document*"

Giới hạn độ sâu tìm kiếm: Giới hạn độ sâu tìm kiếm ở một mức cụ thể bằng tùy chọn -maxdeep.

$ find /home -maxdepth 2 -name "*.txt"

Loại trừ các thư mục cụ thể: Loại trừ các thư mục nhất định khỏi tìm kiếm của bạn bằng cách sử dụng -not hoặc ! lựa chọn.

$ find /home -type f -name "*.txt" -not -path "/home/user/exclude/*"

Remember, mastering the “find” command can significantly enhance your ability to navigate and manage files in a Linux environment. Experiment with different options to tailor your searches according to specific criteria.

Search by file content using “grep” command

When it comes to finding specific content within files, the “grep” command becomes your go-to tool. It allows you to search for patterns or text strings within one or multiple files. Here’s a quick cheatsheet to get you started:

Tìm kiếm nội dung cơ bản: Để tìm kiếm một chuỗi cụ thể trong một tệp, hãy sử dụng cú pháp sau

$ grep "search_string" filename

Replace “search_string” with the text you’re looking for and “filename” with the name of the file.

Tìm kiếm trong nhiều tệp: Nếu bạn muốn tìm kiếm trong nhiều tệp, hãy cung cấp ký tự đại diện hoặc mẫu tệp cụ thể

$ grep "pattern" /path/to/files/*.txt

Tìm kiếm không phân biệt chữ hoa chữ thường: Làm cho tìm kiếm của bạn không phân biệt chữ hoa chữ thường với tùy chọn -i

$ grep -i "pattern" filename

Hiển thị số dòng: Nếu bạn muốn biết số dòng nơi tìm thấy mẫu, hãy sử dụng tùy chọn -n

$ grep -n "pattern" filename

Chỉ hiển thị tên tệp: Để chỉ hiển thị tên của các tệp chứa mẫu, hãy sử dụng tùy chọn -l

$ grep -l "pattern" /path/to/files/*.txt

Tìm kiếm đệ quy: Nếu bạn muốn tìm kiếm mẫu trong tất cả các tệp trong một thư mục và các thư mục con của nó, hãy sử dụng tùy chọn -r

$ grep -r "pattern" /path/to/directory

Loại trừ tệp hoặc thư mục: Exclude certain files or directories from your search with the –exclude option

$ grep "pattern" --exclude=*.log /path/to/files/*

Tìm kiếm toàn bộ từ: Sử dụng tùy chọn -w để tìm kiếm toàn bộ từ, tránh khớp một phần

$ grep -w "word" filename

Advanced “grep” Usage

Tìm kiếm các trận đấu đảo ngược: Đảo ngược kết quả khớp để hiển thị các dòng không chứa mẫu đã chỉ định bằng tùy chọn -v

$ grep -v "pattern" filename

Đếm các trận đấu: Nếu bạn muốn biết có bao nhiêu dòng chứa mẫu, hãy sử dụng tùy chọn -c:

$ grep -c "pattern" filename

Chỉ hiển thị văn bản phù hợp: Chỉ hiển thị văn bản khớp với mẫu bằng tùy chọn -o:

$ grep -o "pattern" filename

Tìm kiếm đệ quy với số dòng: Kết hợp các tùy chọn để tìm kiếm toàn diện, ví dụ:

$ grep -r -n "pattern" /path/to/directory

Mastering the “grep” command allows you to swiftly locate specific content within files, making it an indispensable tool for efficient file exploration in a Linux environment. Experiment with different options to tailor your searches and uncover the information you need.

Phương pháp tìm kiếm tập tin thay thế

In addition to the powerful “find” and “grep” commands, there are alternative methods for searching files in a Linux environment. Let’s explore a few:

Tìm tệp bằng tập lệnh Python

Sometimes, a custom Python script can provide more flexibility in file searching. Here’s a simple example using Python’s osfnmatch modules:

import os
from fnmatch import fnmatch

def find_files(directory, pattern):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if fnmatch(file, pattern):
                print(os.path.join(root, file))

# Usage
find_files('/path/to/search', '*.txt')

This script walks through the directory and its subdirectories, matching files based on the specified pattern. Customize the find_files function to suit your specific search criteria.

The “locate” Command

The “xác định vị trí” command is another efficient way to find files on a Linux system. It uses a pre-built index, making searches faster compared to the “find” command. However, keep in mind that the index needs regular updates to include recent changes.

Cập nhật cơ sở dữ liệu định vị:

$ sudo updatedb

Tìm kiếm tập tin:

$ locate filename.txt

Using the “which” Command

If you’re looking for the location of an executable in your system’s PATH, the “which” command can help.

Tìm vị trí có thể thực thi:

$ which executable_name

Using “fd” – A Fast and User-friendly Alternative to “find”

The “fd” command is a fast and user-friendly alternative to “find.” It comes with a simplified syntax and colorized output.

Cài đặt fd:

$ sudo apt-get install fd-find # For Ubuntu/Debian
$ sudo dnf install fd # For Fedora

Tìm kiếm tập tin:

$ fdfind Documents
Phone/Documents
Documents
Documents.zip

Tập lệnh và bí danh tùy chỉnh

Cuối cùng, bạn có thể tạo tập lệnh shell hoặc bí danh tùy chỉnh để hợp lý hóa quá trình tìm kiếm tệp của mình. Ví dụ:

# Custom Alias
alias findtxt='find /path/to/search -name "*.txt"'

# Usage
$ findtxt

Các tập lệnh và bí danh tùy chỉnh cho phép bạn tạo lối tắt cho nhu cầu tìm kiếm tệp cụ thể của mình, nâng cao quy trình làm việc của bạn.

Tìm tệp trong Linux bằng tập lệnh Bash

Tạo và sử dụng tập lệnh bash giúp tự động hóa các tác vụ tìm kiếm tệp lặp đi lặp lại trong Linux. Dưới đây là ví dụ về tập lệnh Bash đơn giản tìm kiếm tệp dựa trên mẫu được cung cấp:

#!/bin/bash

# Bash script to find files based on a pattern

if [ $# -ne 2 ]; then
echo "Usage: $0 <directory> <pattern>"
exit 1
fi

directory=$1
pattern=$2

# Check if the directory exists
if [ ! -d "$directory" ]; then
echo "Error: Directory $directory not found."
exit 1
fi

# Use find command to search for files
find "$directory" -name "$pattern" -print

Lưu tập lệnh này vào một tệp, ví dụ: find_files.sh và làm cho nó có thể thực thi được bằng lệnh sau:

$ chmod +x find_files.sh

Bây giờ, bạn có thể sử dụng tập lệnh để tìm kiếm tệp bằng cách cung cấp thư mục và mẫu làm đối số:

$ ./find_files.sh /path/to/search "*.txt"

Tập lệnh này kiểm tra xem số lượng đối số có được cung cấp chính xác hay không và liệu thư mục được chỉ định có tồn tại hay không. Sau đó, nó sử dụng lệnh find để tìm kiếm các tệp dựa trên mẫu đã cho.

Phần thưởng: cách tìm kiếm thông qua hình ảnh trong Linux

Trên Linux, có một số công cụ và phương pháp tìm kiếm hình ảnh, mỗi công cụ cung cấp các tính năng và khả năng riêng. Dưới đây là một vài lựa chọn:

“find” Command with File Type Filtering:

The standard “find” command can be used to locate image files based on their file types. For example, to find all JPEG files in a directory and its subdirectories:

$ find /path/to/images -type f -name "*.jpg"

The “fdfind” Command:

The “fdfind” command, a fast and user-friendly alternative to “find,” can also be used to search for image files. Install it if you haven’t already:

$ sudo apt-get install fd-find # For Ubuntu/Debian
$ sudo dnf install fd # For Fedora

Tìm kiếm hình ảnh có phần mở rộng cụ thể:

$ fdfind -e jpg

The “locate” Command

The “locate” command can be used for quick searches, especially if an updated database is maintained:

$ locate '*.jpg'

Hãy nhớ cập nhật cơ sở dữ liệu định vị thường xuyên để biết những thay đổi gần đây:

$ sudo updatedb

“grep” Command for Specific Image Names:

If you have a specific naming convention for your image files, you can use the “grep” command to search for them:

$ grep -r 'pattern' /path/to/images

Replace ‘pattern’ with a part of the image file name.

“file” Command

The “file” command can identify file types, helping you filter out image files:

$ file /path/to/images/*

Look for lines that include “image” to identify image files.

“feh” Image Viewer with Filelist

If you have a list of image files and want to view them, the “feh” image viewer allows you to create a filelist:

$ feh -f $(find /path/to/images -type f -name "*.jpg")

Thao tác này sẽ mở trình xem ảnh với danh sách tệp gồm tất cả các tệp JPEG trong thư mục được chỉ định.

Sử dụng công cụ siêu dữ liệu hình ảnh

If your images have metadata, you can use tools like “exiftool” to search based on image properties:

$ exiftool -filename -r /path/to/images | grep 'search_term'

Trình quản lý tệp đồ họa

Các trình quản lý tệp đồ họa như Nautilus, Dolphin hoặc Thunar thường cung cấp chức năng tìm kiếm. Bạn có thể điều hướng đến thư mục và sử dụng thanh tìm kiếm.

Trình tổ chức hình ảnh dựa trên thẻ

Tools like “digiKam” or “Shotwell” offer image organization based on tags. Tag your images and use these tools to search based on tags.

Tóm tắt

In conclusion, mastering file search on Linux involves understanding and combining various commands, tools, and scripting techniques. Whether you’re a command-line enthusiast or prefer graphical interfaces, this guide equips you with the knowledge to navigate and search for files seamlessly in a Linux environment. Happy file hunting!