Shell 中的 Globbing:原理、使用方法与实现解析(中英双语)

news2025/2/6 18:31:14

Shell 中的 Globbing:原理、使用方法与实现解析

在 Unix Shell(如 Bash、Zsh)中,globbing 是指 文件名模式匹配(filename pattern matching),它允许用户使用特殊的通配符(wildcards)来匹配多个文件,而不需要手动列出所有文件名。这一功能是 Shell 解析命令时的一个重要步骤,极大地提高了命令行操作的灵活性。


1. 什么是 Globbing?

Globbing 是 Shell 解释用户输入的命令时,将包含通配符的模式 扩展为符合匹配规则的文件名列表 的过程。例如:

ls *.txt

在执行 ls *.txt 时,Shell 不会将 *.txt 直接传递给 ls,而是会 先解析 *.txt 并匹配当前目录下的所有 .txt 文件,然后把结果传递给 ls 命令。例如,当前目录下有:

file1.txt file2.txt file3.log

则:

ls *.txt

实际上等价于:

ls file1.txt file2.txt

其中 file3.log 因不符合 *.txt 的模式匹配规则而被排除。


2. Globbing 的常见通配符

Shell 的 globbing 机制支持多种 通配符(wildcards),常见的有以下几种:

通配符作用示例匹配内容
*匹配 任意数量 的字符(包括 0 个字符)*.txta.txtb.txttest.txt
?匹配 任意单个字符file?.txtfile1.txtfile2.txt,但不匹配 file10.txt
[abc]匹配 [] 内的 任意一个字符file[12].txtfile1.txtfile2.txt
[a-z]匹配 某个范围内的字符file[a-z].txtfilea.txtfileb.txt
{a,b,c}匹配 逗号分隔的任意一个模式file{1,2,3}.txtfile1.txtfile2.txtfile3.txt
** (仅 Bash 4.0+)递归匹配所有子目录**/*.txt匹配当前目录及所有子目录中的 .txt 文件

3. Globbing 的执行流程

在 Shell 处理用户输入的命令时,globbing 是命令解析(parsing)过程中的一个步骤。执行流程如下:

  1. 用户输入命令(例如 ls *.txt)。
  2. Shell 解析命令
    • 如果命令行包含通配符(如 *),Shell 进入 globbing 处理
    • Shell 读取当前目录下的文件列表,并 匹配符合规则的文件名
  3. Shell 替换通配符模式
    • *.txt 被替换为所有匹配的文件名,如 file1.txt file2.txt
  4. Shell 执行最终命令
    • ls file1.txt file2.txt

注意:如果没有任何文件匹配通配符模式,大多数 Shell 会直接返回原始模式,如:

echo *.xyz

如果 *.xyz 没有匹配的文件,Bash 会直接输出 *.xyz,而不会报错。


4. Globbing 与 正则表达式 的区别

Globbing 并不是正则表达式,它们有以下主要区别:

特性Globbing正则表达式
作用文件名匹配处理文本模式匹配
* 含义匹配 任意字符(包括空字符)匹配 前一个字符 0 次或多次
? 含义匹配 任意单个字符匹配 前一个字符 0 或 1 次
. 含义作为普通字符匹配代表 任意单个字符

示例:

ls *.txt    # 使用 globbing,匹配所有 .txt 结尾的文件
grep 'a.*b' file.txt   # 使用正则表达式,匹配 'a' 到 'b' 之间的任何字符

5. 禁用 Globbing

有时候,我们希望 Shell 不要 自动展开通配符,而是让命令接收到原始的 *? 等字符。可以使用以下方法:

  1. 使用单引号 ''
    echo '*.txt'  # 输出 *.txt,而不是匹配的文件列表
    
  2. 使用 set -f 关闭 globbing
    set -f
    echo *.txt   # 直接输出 *.txt
    set +f       # 重新开启 globbing
    

6. Shell 中的 Globbing 实现

Globbing 在 Shell 内部是如何实现的呢?主要分为以下几步:

  1. 读取命令:Shell 读取用户输入的命令字符串。
  2. 解析通配符
    • 遍历当前目录文件列表。
    • 依次对文件名进行 模式匹配(Pattern Matching)。
    • 使用 字符串匹配算法 进行匹配,如:
      • * 进行贪心匹配(Greedy Match)。
      • ? 进行单字符匹配。
      • [a-z] 进行范围匹配。
  3. 替换匹配项
    • 匹配的文件列表替换原始通配符字符串。
  4. 执行命令:Shell 执行替换后的命令。

Shell 通常使用 系统调用 opendir()readdir() 访问目录并进行匹配。


7. 编写 C 代码实现简单的 Globbing

下面是一个使用 fnmatch() 函数进行 Shell 风格模式匹配的 C 代码示例:

具体原理和代码解析请看笔者的另一篇博客: 深入解析 fnmatch():C 语言中的模式匹配函数(中英双语)

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <fnmatch.h>

void list_matching_files(const char *pattern) {
    struct dirent *entry;
    DIR *dir = opendir(".");
    
    if (!dir) {
        perror("opendir");
        return;
    }

    while ((entry = readdir(dir)) != NULL) {
        if (fnmatch(pattern, entry->d_name, 0) == 0) {
            printf("%s\n", entry->d_name);
        }
    }
    
    closedir(dir);
}

int main() {
    list_matching_files("*.c");  // 匹配当前目录下的所有 .c 文件
    return 0;
}

运行示例

$ gcc globbing.c -o globbing
$ ./globbing
main.c
utils.c
shell.c

8. 结论

Globbing 是 Shell 解析命令的重要步骤,主要用于 文件名匹配,其实现涉及 字符串匹配算法、系统目录读取 等技术。用户可以利用 通配符 灵活地批量操作文件,但要注意它与 正则表达式 的区别。此外,用户可以通过 单引号set -f 禁用 Globbing,使 Shell 直接传递原始字符串。理解 Globbing 的原理可以帮助我们更高效地使用 Shell 命令,提高自动化任务的执行效率。


这篇博客详细介绍了 Globbing 的概念、用法、实现原理、C 代码示例,希望能帮助你更深入地理解这个 Shell 机制! 🚀

Shell Globbing: Principles, Usage, and Implementation

Globbing in Unix Shell (such as Bash, Zsh) refers to filename pattern matching, where users can use special wildcard characters to match multiple files without manually listing their names. This feature enhances the flexibility of command-line operations.


1. What is Globbing?

Globbing is the process where the Shell expands wildcard patterns into matching filenames before executing a command.

For example, consider the command:

ls *.txt

Instead of passing *.txt as an argument to ls, the Shell first expands the pattern by searching for files in the current directory that match the pattern. If the directory contains:

file1.txt file2.txt file3.log

then the command:

ls *.txt

is actually executed as:

ls file1.txt file2.txt

while file3.log is ignored because it does not match *.txt.


2. Common Wildcards in Globbing

Shell globbing supports several wildcards for flexible pattern matching:

WildcardDescriptionExampleMatches
*Matches any number of characters (including none)*.txta.txt, b.txt, test.txt
?Matches any single characterfile?.txtfile1.txt, file2.txt (not file10.txt)
[abc]Matches any single character in bracketsfile[12].txtfile1.txt, file2.txt
[a-z]Matches any character in the rangefile[a-z].txtfilea.txt, fileb.txt
{a,b,c}Matches any of the comma-separated patternsfile{1,2,3}.txtfile1.txt, file2.txt, file3.txt
** (Bash 4.0+)Recursively matches files in subdirectories**/*.txtAll .txt files in the directory tree

3. How Globbing Works Internally

When a user enters a command, Shell processing follows these steps:

  1. User inputs a command (e.g., ls *.txt).
  2. Shell scans for wildcards:
    • If a command argument contains a wildcard (*, ?, etc.), Shell performs globbing.
    • It retrieves the list of files in the current directory.
    • It matches filenames against the pattern.
  3. Shell replaces the pattern with matching filenames:
    • If *.txt matches file1.txt file2.txt, the final command becomes:
      ls file1.txt file2.txt
      
  4. Shell executes the command.

Note: If no files match, some shells return the original pattern (e.g., echo *.xyz outputs *.xyz).


4. Difference Between Globbing and Regular Expressions

Globbing is not the same as regular expressions. Key differences:

FeatureGlobbingRegular Expressions
PurposeMatches filenamesMatches text patterns
*Matches any charactersMatches previous character zero or more times
?Matches one characterMatches previous character zero or one time
.Treated as a normal characterMatches any character

Example:

ls *.txt         # Uses globbing to list all .txt files
grep 'a.*b' file.txt  # Uses regex to match 'a' followed by 'b'

5. Disabling Globbing

To prevent Shell from expanding wildcards, use:

  1. Single quotes (''):
    echo '*.txt'  # Outputs *.txt without expansion
    
  2. Disable globbing with set -f:
    set -f
    echo *.txt   # Outputs *.txt
    set +f       # Re-enables globbing
    

6. How Globbing is Implemented in Shell

Internally, globbing is handled in these steps:

  1. Shell reads the command string.
  2. Pattern matching against directory contents:
    • It retrieves files using system calls like opendir() and readdir().
    • It applies pattern matching algorithms.
  3. Matches are substituted before executing the command.

7. Implementing Globbing in C

The following C program demonstrates pattern matching using fnmatch(), which applies glob-style matching:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <fnmatch.h>

void list_matching_files(const char *pattern) {
    struct dirent *entry;
    DIR *dir = opendir(".");
    
    if (!dir) {
        perror("opendir");
        return;
    }

    while ((entry = readdir(dir)) != NULL) {
        if (fnmatch(pattern, entry->d_name, 0) == 0) {
            printf("%s\n", entry->d_name);
        }
    }
    
    closedir(dir);
}

int main() {
    list_matching_files("*.c");  // Matches all `.c` files in the directory
    return 0;
}

Example Output

If the directory contains main.c utils.c shell.c, running:

$ gcc globbing.c -o globbing
$ ./globbing
main.c
utils.c
shell.c

8. Conclusion

Globbing is a key feature of Shell parsing, allowing users to efficiently match filenames using wildcards. It differs from regular expressions and is processed before executing commands. Understanding globbing helps users write more efficient command-line operations and scripts. It is implemented at the Shell level using directory scanning and pattern matching algorithms.

Mastering globbing enables more effective batch file operations, automation, and scripting in Unix-based systems! 🚀

后记

2025年2月4日于山东日照。在GPT4o大模型辅助下完成。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2293909.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

互联网行业常用12个数据分析指标和八大模型

本文目录 前言 一、互联网线上业务数据分析的12个指标 1. 用户数据&#xff08;4个&#xff09; (1) 存量&#xff08;DAU/MAU&#xff09; (2) 新增用户 (3) 健康程度&#xff08;留存率&#xff09; (4) 渠道来源 2. 用户行为数据&#xff08;4个&#xff09; (1) 次数/频率…

使用 Ollama 在 Windows 环境部署 DeepSeek 大模型实战指南

文章目录 前言Ollama核心特性 实战步骤安装 Ollama验证安装结果部署 DeepSeek 模型拉取模型启动模型 交互体验命令行对话调用 REST API 总结个人简介 前言 近年来&#xff0c;大语言模型&#xff08;LLM&#xff09;的应用逐渐成为技术热点&#xff0c;而 DeepSeek 作为国产开…

新春贺岁,共赴AGI之旅

点击蓝字 关注我们 AI TIME欢迎每一位AI爱好者的加入&#xff01; 往期精彩文章推荐 季姮教授独家文字版干货 | 面向知识渊博的大语言模型 关于AI TIME AI TIME源起于2019年&#xff0c;旨在发扬科学思辨精神&#xff0c;邀请各界人士对人工智能理论、算法和场景应用的本质问题…

C_位运算符及其在单片机寄存器的操作

C语言的位运算符用于直接操作二进制位&#xff0c;本篇简单结束各个位运算符的作业及其在操作寄存器的应用场景。 一、位运算符的简单说明 1、按位与运算符&#xff08;&&#xff09; 功能&#xff1a;按位与运算符对两个操作数的每一位执行与操作。如果两个对应的二进制…

Java面试题集合篇5:10道基础面试题

文章目录 前言41、多线程使用 ArrayList42、List 和 Set 区别43、HashSet 实现原理44、HashSet检查重复和保证数据不可重复45、BlockingQueue46、Map接口46.1、HashMap实现原理46.2、HashMap在JDK1.7和JDK1.8中不同点46.3、JDK1.7 VS JDK1.8 比较 47、HashMap的put方法流程48、…

汽车加气站操作工试题及答案​

1.天然气的主要成分是&#xff08; &#xff09;​ A. 乙烷 B. 乙烯 C. 甲烷 D. 乙炔​ 答案&#xff1a;C​ 2.加气站中&#xff0c;用来储存天然气的设备是&#xff08; &#xff09;​ A. 加气机 B. 压缩机 C. 储气井 D. 脱水装置​ 答案&#xff1a;C​ 3.以下哪…

企业四要素如何用PHP进行调用

一、什么是企业四要素&#xff1f; 企业四要素接口是在企业三要素&#xff08;企业名称、统一社会信用代码、法定代表人姓名&#xff09;的基础上&#xff0c;增加了一个关键要素&#xff0c;通常是企业注册号或企业银行账户信息。这种接口主要用于更全面的企业信息验证&#x…

【大数据技术】搭建完全分布式高可用大数据集群(Hadoop+MapReduce+Yarn)

搭建完全分布式高可用大数据集群(Hadoop+MapReduce+Yarn) jdk-8u361-linux-x64.tarhadoop-3.3.6.tar.gz注:请在阅读本篇文章前,将以上资源下载下来。 写在前面 本文主要介绍搭建完全分布式高可用集群Hadoop+MapReduce+Yarn的详细步骤。 注意: 统一约定将软件安装包存放…

【MySQL】MySQL经典面试题深度解析

文章目录 一、MySQL与C的深度结合1.1 为什么C项目需要MySQL&#xff1f;1.2 典型应用场景 二、基础概念面试题精讲2.1 存储引擎对比2.2 索引原理 三、C专项面试题解析3.1 连接池实现3.2 预处理语句3.3 批量操作优化 四、高级应用面试题剖析4.1 事务隔离级别4.2 锁机制详解4.3 查…

GitHub Copilot 越狱漏洞

研究人员发现了两种操控 GitHub 的人工智能&#xff08;AI&#xff09;编码助手 Copilot 的新方法&#xff0c;这使得人们能够绕过安全限制和订阅费用、训练恶意模型等。 第一种技巧是将聊天交互嵌入 Copilot 代码中&#xff0c;利用 AI 的问答能力&#xff0c;使其产生恶意输…

UE虚幻引擎No Google Play Store Key:No OBB found报错如何处理

UE虚幻引擎No Google Play Store Key&#xff1a;No OBB found报错如何处理&#xff1f; 问题描述&#xff1a; UE成功打包APK并安装过后&#xff0c;启动应用时提示&#xff1a; No Google Play Store KeyNo OBB found and no store key to try to download. Please setone …

吴恩达深度学习——卷积神经网络实例分析

内容来自https://www.bilibili.com/video/BV1FT4y1E74V&#xff0c;仅为本人学习所用。 文章目录 LeNet-5AlexNetVGG-16ResNets残差块 1*1卷积 LeNet-5 输入层&#xff1a;输入为一张尺寸是 32 32 1 32321 32321的图像&#xff0c;其中 32 32 3232 3232是图像的长和宽&…

LabVIEW的智能电源远程监控系统开发

在工业自动化与测试领域&#xff0c;电源设备的精准控制与远程管理是保障系统稳定运行的核心需求。传统电源管理依赖本地手动操作&#xff0c;存在响应滞后、参数调节效率低、无法实时监控等问题。通过集成工业物联网&#xff08;IIoT&#xff09;技术&#xff0c;实现电源设备…

【自动化办公】批量图片PDF自定义指定多个区域识别重命名,批量识别铁路货物运单区域内容改名,基于WPF和飞桨ocr深度学习模型的解决方案

项目背景介绍 铁路货运企业需要对物流单进行长期存档&#xff0c;以便后续查询和审计。不同的物流单可能包含不同的关键信息&#xff0c;通过自定义指定多个区域进行识别重命名&#xff0c;可以使存档的图片文件名具有统一的规范和明确的含义。比如&#xff0c;将包含货物运单…

neo4j-在Linux中安装neo4j

目录 切换jdk 安装neo4j 配置neo4j以便其他电脑可以访问 切换jdk 因为我安装的jdk是1.8版本的&#xff0c;而我安装的neo4j版本为5.15,Neo4j Community 5.15.0 不支持 Java 1.8&#xff0c;它要求 Java 17 或更高版本。 所以我需要升级Java到17 安装 OpenJDK 17 sudo yu…

专业学习|通过案例了解蒙特卡罗模拟实操步骤与含义

一、蒙特卡罗模拟介绍 蒙特卡罗模拟&#xff08;Monte Carlo Simulation&#xff09;是一种基于随机采样的数值计算方法&#xff0c;用于解决具有不确定性或复杂概率分布的问题。其核心思想是通过多次随机抽样来逼近系统的行为或目标函数的真实值&#xff0c;进而对系统进行评估…

数据结构【链栈】

基于 C 实现链表栈&#xff1a;原理、代码与应用 一、引言 栈就是一个容器&#xff0c;可以当场一个盒子&#xff0c;只能一个一个拿&#xff0c;一个一个放&#xff0c;而且是从上面放入。 有序顺序栈操作比较容易【会了链栈之后顺序栈自然明白】&#xff0c;所以我们这里只…

人工智能|本地部署|ollama+chatbox快速Windows10下部署(初级篇)

一、 前言&#xff1a; 其实早一个月我已经使用过deepseek&#xff0c;并且也在自己的机器上通过ollama部署过&#xff0c;但一直没有太多动力&#xff0c;现在感觉还是的记录一下&#xff0c;省的自己给忘掉了 本文只是简单记录一下ollamaopen-webuichatbox部署通过网盘分享…

Android Studio 下载安装教程(2024 更新版),附详细图文

今天&#xff0c;为大家带来的是Android Studio 2024更新版的下载安装教程&#xff0c;包含详细图文步骤。 随着 Android Studio 的不断更新&#xff0c;自从引入 Koala 系列后&#xff0c;其版本号的命名规则也发生了变化。以本次更新为例&#xff0c;版本号为 2024.2.1&#…

6.【BUUCTF】[SUCTF 2019]CheckIn

打开题目页面如下 看样子是一道有关文件上传的题 上传一句话木马 显示&#xff1a;非法后缀&#xff01; 看来.php后缀被过滤了 上传一张带有木马的照片 在文件地址处输入cmd 输入以下代码执行 copy 1.jpg/b4.php/a 5.jpg 最后一行有一句话木马 上传带有木马的图片 但其实…