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

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 directoryreturn 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.mzph.cn/bicheng/70113.shtml

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

相关文章

7 与mint库对象互转宏(macros.rs)

macros.rs代码定义了一个Rust宏mint_vec&#xff0c;它用于在启用mint特性时&#xff0c;为特定的向量类型实现与mint库中对应类型的相互转换。mint库是一个提供基本数学类型&#xff08;如点、向量、矩阵等&#xff09;的Rust库&#xff0c;旨在与多个图形和数学库兼容。这个宏…

P3078[USACO13MAR] Poker Hands S

P3078[USACO13MAR] Poker Hands S https://www.luogu.com.cn/problem/P3078 前言 学习差分后写的第一道题&#xff0c;直接给我干懵逼&#xff0c;题解都看不懂……吃了个晚饭后开窍写出来了&#xff0c;遂成此篇。 题目 翻译版本 Bessie 和她的朋友们正在玩一种独特的扑克游…

【物联网】ARM核常用指令(详解):数据传送、计算、位运算、比较、跳转、内存访问、CPSR/SPSR

文章目录 指令格式&#xff08;重点&#xff09;1. 立即数2. 寄存器位移 一、数据传送指令1. MOV指令2. MVN指令3. LDR指令 二、数据计算指令1. ADD指令1. SUB指令1. MUL指令 三、位运算指令1. AND指令2. ORR指令3. EOR指令4. BIC指令 四、比较指令五、跳转指令1. B/BL指令2. l…

Redis基础(二)——通用命令与五大基本数据类型

目录 一、Redis数据结构基本介绍 二、Redis通用命令 1.查看通用命令 2.KEYS&#xff1a;查看符合模板的所有key 3.DEL&#xff1a;删除指定的Key 4.lEXISTS&#xff1a;判断key是否存在 5.lEXPIRE&#xff1a;给一个key设置有效期&#xff0c;有效期到期时该key会被自…

Ajax:重塑Web交互体验的人性化探索

在数字化时代&#xff0c;网页的交互性和响应速度已成为衡量用户体验的关键指标。Ajax&#xff08;Asynchronous JavaScript and XML&#xff09;&#xff0c;作为前端与后端沟通的桥梁&#xff0c;凭借其异步通信的能力&#xff0c;极大地提升了网页的动态性和用户友好度&…

ComfyUI工作流 参考图像生成人像手办(SDXL版)

文章目录 参考图像生成人像手办SD模型Node节点工作流程效果展示开发与应用参考图像生成人像手办 此工作流旨在实现将图像生成高精度的3D手办风格效果,通过深度学习技术完成从图像处理、模型加载、提示词优化到图像生成和超分辨率处理的一系列操作。整个流程以SDXL模型为核心,…

c语言 程序计算圆的面积(Program to find area of a circle)

给定圆的半径&#xff0c;求该圆的面积。 可以使用以下公式简单地计算圆的面积。 其中 r 是圆的半径&#xff0c;它可能是浮点数&#xff0c;因为饼图的值为 3.14 方法&#xff1a;使用给定的半径&#xff0c;使用上述公式找到面积&#xff1a;&#xff08;pi * r * r&#…

解析PHP文件路径相关常量

PHP文件路径相关常量包括以下几个常量&#xff1a; __FILE__&#xff1a;表示当前文件的绝对路径&#xff0c;包括文件名。 __DIR__&#xff1a;表示当前文件所在的目录的绝对路径&#xff0c;不包括文件名。 dirname(__FILE__)&#xff1a;等同于__DIR__&#xff0c;表示当前…

Rust错误处理:从灭火器到核按钮的生存指南

开篇&#xff1a;错误处理的生存哲学 在Rust的平行宇宙里&#xff0c;错误分为两种人格&#xff1a; panic! → 核按钮&#x1f4a3;&#xff08;不可恢复&#xff0c;全系统警报&#xff09;Result → 灭火器&#x1f9ef;&#xff08;可控制&#xff0c;局部处理&#xff0…

蓝桥杯C语言组:暴力破解

基于C语言的暴力破解方法详解 暴力破解是一种通过穷举所有可能的解来找到正确答案的算法思想。在C语言中&#xff0c;暴力破解通常用于解决那些问题规模较小、解的范围有限的问题。虽然暴力破解的效率通常较低&#xff0c;但它是一种简单直接的方法&#xff0c;适用于一些简单…

基于STM32的智能安防监控系统

1. 引言 随着物联网技术的普及&#xff0c;智能安防系统在家庭与工业场景中的应用日益广泛。本文设计了一款基于STM32的智能安防监控系统&#xff0c;集成人体感应、环境异常检测、图像识别与云端联动功能&#xff0c;支持实时报警、远程监控与数据回溯。该系统采用边缘计算与…

【环境搭建】1.1源码下载与同步

目录 写在前面 一&#xff0c;系统要求 二&#xff0c;安装depot_tools 三&#xff0c;获取代码 四&#xff0c;代码同步 五&#xff0c;代码结构 写在前面 当前的开发背景是基于Google的开源Chromium&#xff0c;来开发Android设备的浏览器方案。 一&#xff0c;系统要…

Image Resize:强大的在线图像处理工具

Image Resize 是一款免费的在线批量图像处理工具&#xff0c;让你轻松调整图像大小、裁剪、压缩&#xff0c;支持多种格式。 批量处理&#xff1a;一次编辑多个图像&#xff0c;提高工作效率。多种格式支持&#xff1a;支持PNG、JPG等多种常见图像格式&#xff0c;满足不同需求…

Pyside/Pyqt 全部类的层级关系

PySide&#xff08;如PySide6&#xff09;的类层级结构基于Qt框架&#xff0c;以下是主要模块及其核心类的层级关系概览。由于类数量庞大&#xff0c;此处仅列出关键类和继承关系&#xff1a; 1. QtCore 模块 基础类与工具 QObject (所有Qt对象的基类) QCoreApplication (控制…

【Linux系统】CPU指令集 和 Linux系统权限 ring 0 / ring 3

CPU 指令集 CPU 指令集&#xff1a;是 CPU 实现软件指挥硬件执行的媒介&#xff0c;具体来说每一条汇编语句都对应了一条CPU指令&#xff0c;而非常非常多的 CPU 指令在一起&#xff0c;可以组成一个、甚至多个集合&#xff0c;指令的集合叫CPU指令集。 CPU 指令集有权限分级&…

Slint的学习

Slint是什么 Slint是一个跨平台的UI工具包&#xff0c;支持windows,linux,android,ios,web&#xff0c;可以用它来构建申明式UI,后端代码支持rust,c,python,nodejs等语言。 开源地址&#xff1a;https://github.com/slint-ui/slint 镜像地址&#xff1a;https://kkgithub.com/…

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

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

九. Redis 持久化-RDB(详细讲解说明,一个配置一个说明分析,步步讲解到位)

九. Redis 持久化-RDB(详细讲解说明&#xff0c;一个配置一个说明分析&#xff0c;步步讲解到位) 文章目录 九. Redis 持久化-RDB(详细讲解说明&#xff0c;一个配置一个说明分析&#xff0c;步步讲解到位)1. RDB 概述2. RDB 持久化执行流程3. RDB 的详细配置4. RDB 备份&恢…

[权限提升] Windows 提权 维持 — 系统错误配置提权 - Trusted Service Paths 提权

关注这个专栏的其他相关笔记&#xff1a;[内网安全] 内网渗透 - 学习手册-CSDN博客 0x01&#xff1a;Trusted Service Paths 提权原理 Windows 的服务通常都是以 System 权限运行的&#xff0c;所以系统在解析服务的可执行文件路径中的空格的时候也会以 System 权限进行解析&a…

4 前置技术(下):git使用

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言 前言