[Shell command collection document editing] Linux text search look command usage guide


Shell Command Column: Full Analysis of Linux Shell Commands


describe


The look command is a text search tool in the Linux system, which is used to find words beginning with a specified string in a specified file or standard input. Its basic syntax is as follows:

grammatical format

look [选项] [模式] [文件...]

Parameter Description

  • -f: Ignoring case, find words that match the pattern.
  • -t: Only show the beginning of the word, not the full content.
  • -b: Only show the end of the word, not the full content.

error condition

  • If the given file does not exist or cannot be accessed, an error message will be displayed.
  • If no mode or file arguments are provided, an error message will be displayed.
  • If no matching word is found, no error message is displayed, but nothing is output.

Precautions

When using the look command of the Linux shell, there are some things to pay attention to:

  1. The look command can only be used to find files sorted in lexicographical order. The look command may not work properly if the file is not sorted.

  2. The look command is case sensitive by default. If you need to lookup regardless of case, you can use -foption.

  3. The look command can only find words that begin with a letter or number. If you need to find words starting with other characters, you can use regular expressions.

  4. The look command can only find exact words. If you need to find words that partially match, you can use regular expressions.

  5. The look command can search multiple files at the same time, and multiple files are separated by spaces.

  6. The look command displays the full content of matched words by default. If you want to show only the beginning or end of a word, you can use the -tor -boption.

  7. The look command will not display an error message, and will output nothing if no matching word is found.

  8. The look command supports wildcards, which can be used in patterns *and ?for fuzzy matching.

  9. The look command can be used in conjunction with other commands, for example to pipe the lookup results to other commands for further processing.

  10. When using the look command, you need to ensure that you have sufficient permissions to access the file you are looking for.

The above are some things to pay attention to when using the look command of the Linux Shell. According to the specific usage scenarios and requirements, you can also refer to the man manual or use the look --helpcommand to obtain more information.


underlying implementation

In the Linux shell, the underlying implementation of the look command is to quickly find words in a lexicographically sorted file by using a binary search algorithm.

Specifically, the look command will first open the file to be searched according to the specified file path, and read it into the memory. It then performs a binary lookup in the file based on keywords provided by the user.

The basic idea of ​​the binary search algorithm is to divide the range to be searched in half, then determine which half the keyword is in, and continue to search in that half. In this way, each search can reduce the search range by half, so as to quickly locate the position of the keyword.

In the look command, it first reads each line in the file and extracts the first word of each line. It then does a binary lookup among these words based on the key words provided by the user.

Since the look command requires that the files have been sorted in dictionary order, it can take advantage of the binary search algorithm to quickly locate the position of the keyword.

Once a matching word is found, the look command outputs the line in its entirety to standard output. If no matching word is found, nothing is output.

To sum up, the underlying implementation of the look command is to quickly locate the words in the dictionary sorting file through the binary search algorithm, and output the matching results. This implementation can efficiently find specified words in large-scale files.


example

example one

Find words in a file that start with "apple" and display the full content:

look apple file.txt

Example two

Find words starting with "hello" in standard input, ignoring case:

echo "Hello, how are you?" | look -f hello

Example three

Find words in a file that start with "world" and display only the beginning of the word:

look -t world file.txt

Example four

Find words starting with "linux" in standard input, and display only the beginning of the word:

echo "Linux is an operating system" | look -t linux

Example five

Find words in a file that end with "program" and display only the ending part of the word:

look -b program file.txt

Example six

Find words ending with "example" in standard input, and display only the ending part of the word:

echo "This is an example" | look -b example

Example seven

Find words starting with "test" in standard input, ignoring case:

echo "Testing is important" | look -f test

implemented in c language


The following is a sample code for implementing the look command in C language, including detailed annotations:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LENGTH 256

// 二进制查找函数
int binarySearch(char *word, FILE *file) {
    
    
    int low = ftell(file);  // 获取当前文件指针位置
    fseek(file, 0, SEEK_END);  // 将文件指针移动到文件末尾
    int high = ftell(file);  // 获取文件末尾位置
    int mid, cmp;

    while (low < high) {
    
    
        mid = (low + high) / 2;
        fseek(file, mid, SEEK_SET);  // 将文件指针移动到中间位置
        while (fgetc(file) != '\n') {
    
    
            if (ftell(file) <= low || ftell(file) >= high) {
    
    
                break;
            }
        }
        if (ftell(file) <= low || ftell(file) >= high) {
    
    
            break;
        }
        char line[MAX_LENGTH];
        fgets(line, MAX_LENGTH, file);
        line[strlen(line) - 1] = '\0';  // 去除行尾的换行符
        cmp = strcmp(line, word);
        if (cmp == 0) {
    
    
            return 1;  // 找到匹配的单词
        } else if (cmp < 0) {
    
    
            low = ftell(file);
        } else {
    
    
            high = ftell(file);
        }
    }
    return 0;  // 未找到匹配的单词
}

// look命令实现函数
void look(char *word, char *filename) {
    
    
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
    
    
        printf("Error opening file.\n");
        return;
    }

    while (!feof(file)) {
    
    
        char line[MAX_LENGTH];
        fgets(line, MAX_LENGTH, file);
        line[strlen(line) - 1] = '\0';  // 去除行尾的换行符
        if (strncmp(line, word, strlen(word)) == 0) {
    
    
            printf("%s\n", line);  // 输出匹配的行
        } else if (strcmp(line, word) > 0) {
    
    
            break;  // 已经超过了匹配的范围,停止查找
        }
    }

    fclose(file);
}

int main(int argc, char *argv[]) {
    
    
    if (argc != 3) {
    
    
        printf("Usage: ./look <word> <filename>\n");
        return 1;
    }

    char *word = argv[1];
    char *filename = argv[2];

    look(word, filename);

    return 0;
}

In this sample code, we have used a binarySearchfunction to implement the binary lookup algorithm. The function takes a word and a lexicographically sorted file as arguments and returns whether a matching word was found.

lookfunction is the function that actually implements the look command. It takes a word and a filename as arguments and looks for matching lines in the file and outputs them.

In mainthe function, we first check that the number of command line arguments is correct. Then, we pass command-line arguments to lookthe function to perform the lookup.

Note: This is just a simple sample code, some special cases (such as file does not exist or file format error) are not considered. In practice, it may be necessary to add more error handling and bounds checking to improve the robustness of the code.


epilogue

During our exploration, we have gained insight into the power and wide application of shell commands. However, learning these techniques is just the beginning. The real power comes in how you incorporate them into your daily work to increase efficiency and productivity.

Psychology tells us that learning is a continuous and engaged process. So, I encourage you not only to read and understand these commands, but also to practice them. Try creating your own commands and gradually master shell programming as part of your daily routine.

Also, remember that sharing is a very important part of the learning process. If you find this blog helpful to you, please like it and leave a comment. Sharing your own problems or interesting experiences when using Shell commands can help more people learn from them.
Also, I welcome you to bookmark this blog and check back anytime. Because review and repeated practice are also the key to consolidating knowledge and improving skills.

Finally, remember: Everyone can become an expert in Shell programming through continuous learning and practice. I look forward to seeing you make even more progress on this journey!


Read my CSDN homepage to unlock more exciting content: Bubble's CSDN homepage

insert image description here

Guess you like

Origin blog.csdn.net/qq_21438461/article/details/131368059