find/grep

老是忘,写一写

find . -name 'filename' 在当前目录下递归查找文件名为filename的文件


grep -r 'grepString' ./ 在当前目录下递归查找包含grepString的文件

#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <string.h> #include <unistd.h> void process_file(const char *filename) { int pipefd[2]; if (pipe(pipefd) == -1) { perror("pipe"); exit(EXIT_FAILURE); } pid_t pid = fork(); if (pid == -1) { perror("fork"); close(pipefd[0]); close(pipefd[1]); exit(EXIT_FAILURE); } if (pid == 0) { // 子进程 close(pipefd[0]); dup2(pipefd[1], STDOUT_FILENO); close(pipefd[1]); execl("/bin/grep", "grep", "-Ei", "error|fail", filename, NULL); // 使用grep查找error或fail[^3] perror("execl"); exit(EXIT_FAILURE); } else { // 父进程 close(pipefd[1]); char buffer[1024]; ssize_t bytes_read; int match_found = 0; while ((bytes_read = read(pipefd[0], buffer, sizeof(buffer) - 1)) > 0) { buffer[bytes_read] = '\0'; printf("%s", buffer); match_found = 1; } close(pipefd[0]); wait(NULL); if (!match_found) { execl("/bin/grep", "grep", "-q", "RNG", filename); // 检查是否包含'RNG'[^4] perror("execl"); exit(EXIT_FAILURE); } } } int main() { DIR *dir; struct dirent *entry; dir = opendir("/var/log/"); if (dir == NULL) { perror("opendir"); return EXIT_FAILURE; } while ((entry = readdir(dir)) != NULL) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } char full_path[1024]; snprintf(full_path, sizeof(full_path), "/var/log/%s", entry->d_name); FILE *file = fopen(full_path, "r"); if (file == NULL) { continue; } fclose(file); char command[256]; snprintf(command, sizeof(command), "/bin/grep -q 'hardware' %s", full_path); int ret = system(command); // 检查文件是否包含'hardware'[^5] if (ret == 0) { process_file(full_path); } } closedir(dir); // 如果没有任何匹配项,则输出"No Device Failure" execl("/bin/grep", "grep", "-q", "error|fail", "/var/log/*", NULL); printf("No Device Failure\n"); return EXIT_SUCCESS; } 会报 /bin/grep: /var/log/cups: ▒▒һ▒▒Ŀ¼ /bin/grep: /var/log/chrony: ▒▒һ▒▒Ŀ¼ /bin/grep: /var/log/sa: ▒▒һ▒▒Ŀ¼ /bin/grep: /var/log/firebird: ▒▒һ▒▒Ŀ¼ /bin/grep: /var/log/lightdm: ▒▒һ▒▒Ŀ¼ /bin/grep: /var/log/iptraf-ng: ▒▒һ▒▒Ŀ¼ /bin/grep: /var/log/glusterfs: ▒▒һ▒▒Ŀ¼ /bin/grep: /var/log/anaconda: ▒▒һ▒▒Ŀ¼ /bin/grep: /var/log/samba: ▒▒һ▒▒Ŀ¼ /bin/grep: /var/log/tuned: ▒▒һ▒▒Ŀ¼ /bin/grep: /var/log/atop: ▒▒һ▒▒Ŀ¼ /bin/grep: /var/log/swtpm: ▒▒һ▒▒Ŀ¼ /bin/grep: /var/log/ntpstats: ▒▒һ▒▒Ŀ¼ grep: /var/log/*: û▒▒▒Ǹ▒▒ļ▒▒▒Ŀ¼ 这些文件是一个目录,怎么处理
最新发布
06-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值