Linux fgrep 命令使用详解

简介

fgrepfix GREP)命令搜索固定字符串,而不将特殊字符解释为正则表达式。它相当于 grep -F

基础语法

shell 复制代码
fgrep [OPTIONS] "STRING" FILE

或

grep -F [OPTIONS] "STRING" FILE

示例用法

在文件中查找包含"error"的所有行

shell 复制代码
fgrep "error" logfile.txt

或

grep -F "error" logfile.txt

搜索多个字符串

keywords.txt 文件包含以下内容:

shell 复制代码
error
warning
failed
shell 复制代码
fgrep -f keywords.txt logfile.txt

或
grep -F -f keywords.txt logfile.txt

# 这将匹配 logfile.txt 中包含以上keywords.txt中的任何单词

搜索包含特殊字符的字符串

grep 不同,fgrep 不会将 . * [] 视为特殊正则表达式字符。 例如,在文件中搜索 1.2.3

shell 复制代码
fgrep "1.2.3" file.txt

或

grep -F "1.2.3" file.txt

# 使用 grep 时,需要转义(grep "1\.2\.3"),但 fgrep 将其视为文字

在多个文件中搜索

shell 复制代码
fgrep "error" file1.txt file2.txt

或

grep -F "error" file1.txt file2.txt

大小写不敏感搜索

shell 复制代码
fgrep -i "error" logfile.txt

或

grep -F -i "error" logfile.txt

统计匹配行数 (-c)

shell 复制代码
fgrep -c "error" logfile.txt

或

grep -F -c "error" logfile.txt

显示行号

shell 复制代码
fgrep -n "error" logfile.txt

或

grep -F -n "error" logfile.txt

# 这将打印匹配的行及其行号

反转匹配(-v 表示排除)

shell 复制代码
fgrep -v "error" logfile.txt

或

grep -F -v "error" logfile.txt

# 排除包含"error"的行

合并选项使用

  • 不区分大小写地查找"error",显示行号,并计算出现次数
shell 复制代码
fgrep -i -n -c "error" logfile.txt

或

grep -F -i -n -c "error" logfile.txt
相关推荐
Yogurt_cry2 小时前
[树莓派4B] 闲置近10年的爱普生 L310 打印机爆改无线打印机
linux·物联网·树莓派
Johny_Zhao1 天前
OpenClaw中级到高级教程
linux·人工智能·信息安全·kubernetes·云计算·yum源·系统运维·openclaw
Sheffield2 天前
Docker的跨主机服务与其对应的优缺点
linux·网络协议·docker
Sheffield2 天前
Alpine是什么,为什么是Docker首选?
linux·docker·容器
Johny_Zhao3 天前
centos7安装部署openclaw
linux·人工智能·信息安全·云计算·yum源·系统运维·openclaw
haibindev3 天前
在 Windows+WSL2 上部署 OpenClaw AI员工的实践与踩坑
linux·wsl2·openclaw
0xDevNull4 天前
Linux切换JDK版本详细教程
linux
进击的丸子4 天前
虹软人脸服务器版SDK(Linux/ARM Pro)多线程调用及性能优化
linux·数据库·后端
Johny_Zhao6 天前
OpenClaw安装部署教程
linux·人工智能·ai·云计算·系统运维·openclaw