a magnifying glass searching through text

Linux에서 파일을 찾는 방법: Find 및 Grep 명령 익히기

이 기사에서는 다양한 도구를 사용하여 Linux에서 파일을 찾는 방법을 배웁니다.

The “find” command cheatsheet

파일 이름으로 검색하기

“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

수정일자로 검색하기

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

$ find /home -mtime 0

예를 들어 10일 전에 수정된 사진을 찾아보겠습니다.

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

파일 형식으로 검색하기

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

디렉토리 검색: 지정된 경로 내의 모든 디렉터리를 찾으려면 -type d 옵션을 사용합니다.

$ find /home -type d

일반 파일 검색: 반대로, 일반 파일을 찾으려면 -type f 옵션을 사용하십시오.

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

심볼릭 링크 검색: 심볼릭 링크를 검색하려면 -type l 옵션을 사용하세요.

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

특정 파일 확장자 검색: 파일 확장자를 지정하여 검색 범위를 좁히세요.

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

결합기준

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

특정 확장자를 가진 수정된 파일 검색: Find files modified in the last 7 days with the extension “.log”.

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

특정 날짜 범위 사이에 수정된 파일 검색: 2023년 11월 1일부터 2023년 11월 5일 사이에 수정된 파일을 찾습니다.

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

Additional “find” Command Options

대소문자 구분 무시: 검색 시 대소문자를 구분하지 않으려면 -iname 옵션을 사용하십시오.

$ find /home -iname "document*"

검색 깊이 제한: -max깊이 옵션을 사용하여 검색 깊이를 특정 수준으로 제한합니다.

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

특정 디렉터리 제외: -not 또는 !를 사용하여 검색에서 특정 디렉토리를 제외하십시오. 옵션.

$ 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:

기본 콘텐츠 검색: 파일에서 특정 문자열을 검색하려면 다음 구문을 사용하십시오.

$ grep "search_string" filename

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

여러 파일에서 검색: 여러 파일을 검색하려면 와일드카드나 특정 파일 패턴을 제공하세요.

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

대소문자를 구분하지 않는 검색: -i 옵션을 사용하여 검색에서 대소문자를 구분하지 않도록 설정하세요.

$ grep -i "pattern" filename

표시 줄 번호: 패턴이 발견된 줄 번호를 알고 싶다면 -n 옵션을 사용하세요.

$ grep -n "pattern" filename

파일 이름만 표시: 패턴이 포함된 파일 이름만 표시하려면 -l 옵션을 사용하세요.

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

재귀적으로 검색: 디렉토리 및 하위 디렉토리 내의 모든 파일에서 패턴을 검색하려면 -r 옵션을 사용하십시오.

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

파일 또는 디렉터리 제외: Exclude certain files or directories from your search with the –exclude option

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

전체 단어 검색: 전체 단어를 검색하려면 -w 옵션을 사용하여 부분 일치를 방지합니다.

$ grep -w "word" filename

Advanced “grep” Usage

반전된 일치 항목 검색: -v 옵션을 사용하여 지정된 패턴을 포함하지 않는 행을 표시하도록 일치 항목을 반전시킵니다.

$ grep -v "pattern" filename

일치 항목 계산: 패턴이 포함된 행 수를 알고 싶다면 -c 옵션을 사용하십시오.

$ grep -c "pattern" filename

일치하는 텍스트만 표시: -o 옵션을 사용하여 패턴과 일치하는 텍스트만 표시합니다.

$ grep -o "pattern" filename

줄 번호를 사용한 재귀 검색: 포괄적인 검색을 위해 옵션을 결합합니다. 예:

$ 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.

대체 파일 검색 방법

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:

Python 스크립트를 사용하여 파일 찾기

Sometimes, a custom Python script can provide more flexibility in file searching. Here’s a simple example using Python’s os 그리고 fnmatch 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 “위치하고 있다” 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.

데이터베이스 찾기 업데이트:

$ sudo updatedb

파일 검색:

$ 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.

실행 파일 위치 찾기:

$ 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.

fd를 설치합니다:

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

파일 검색:

$ fdfind Documents
Phone/Documents
Documents
Documents.zip

사용자 정의 스크립트 및 별칭

마지막으로 사용자 정의 셸 스크립트나 별칭을 만들어 파일 검색 프로세스를 간소화할 수 있습니다. 예를 들어:

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

# Usage
$ findtxt

사용자 정의 스크립트 및 별칭을 사용하면 특정 파일 검색 요구에 맞는 바로가기를 생성하여 작업 흐름을 향상할 수 있습니다.

Bash 스크립트를 사용하여 Linux에서 파일 찾기

Bash 스크립트를 생성하고 사용하면 Linux에서 반복적인 파일 검색 작업을 자동화하는 데 도움이 됩니다. 다음은 제공된 패턴을 기반으로 파일을 검색하는 간단한 Bash 스크립트의 예입니다.

#!/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

이 스크립트를 find_files.sh와 같은 파일에 저장하고 다음 명령을 사용하여 실행 가능하게 만듭니다.

$ chmod +x find_files.sh

이제 스크립트를 사용하여 디렉터리와 패턴을 인수로 제공하여 파일을 검색할 수 있습니다.

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

이 스크립트는 올바른 수의 인수가 제공되었는지와 지정된 디렉터리가 존재하는지 확인합니다. 그런 다음 find 명령을 사용하여 주어진 패턴을 기반으로 파일을 검색합니다.

보너스: Linux에서 이미지를 검색하는 방법

Linux에는 이미지 검색을 위한 여러 가지 도구와 방법이 있으며 각각 고유한 특징과 기능을 제공합니다. 다음은 몇 가지 옵션입니다.

“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

특정 확장자를 가진 이미지 검색:

$ fdfind -e jpg

The “locate” Command

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

$ locate '*.jpg'

최근 변경 사항에 대해 정기적으로 위치 데이터베이스를 업데이트하는 것을 잊지 마십시오.

$ 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")

그러면 지정된 디렉터리에 있는 모든 JPEG 파일의 파일 목록이 포함된 이미지 뷰어가 열립니다.

이미지 메타데이터 도구 사용

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'

그래픽 파일 관리자

Nautilus, Dolphin 또는 Thunar와 같은 그래픽 파일 관리자는 종종 검색 기능을 제공합니다. 해당 디렉토리로 이동하고 검색창을 사용할 수 있습니다.

태그 기반 이미지 정리 도구

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

요약

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!