1. Grep
语法
grep pattern filename
pattern 参考简单正则
参数
| 参数 | 函数 |
|---|---|
| -i | 忽略大小写 |
| -w | 全词匹配 |
| -r/R | 递归匹配文件夹中文件 |
| -n | 显示行号 |
| -c | 显示匹配行数 |
| -v | 显示不匹配的行 |
| -l | 显示匹配的文件名 |
grep -i -l -r "Student" /src/ --color
src/stu.cpp
2. Sed
2.1 原理

sed 按行取文本,依次执行命令集中的每条命令,最后将命令输出。
Sed 命令模式:地址 + 动作
2.2 参数
| 参数 | 含义 |
|---|---|
| -n | 抑制sed**默认**输出 |
| -e | 指定表达式 |
| -f | 指定sed脚本 |
| -r | 使用ere正则表达式,默认采用gnu扩展bre |
| -i | in-place 修改,即修改作用于原文件 |
NOTE:
-n抑制默认输出,默认情况下,sed处理一行,输出一行,即使这行没有作用任何命令。
-n 与 -i 不能同时使用,-n 抑制sed输出,而-i又需要输出。
-e 指定多个表达式,如sed -e "/abc/p" -e "/bcd/p" text
-e 可以通过分号,省略-e, 如sed "/abc/p;/bcd/p" text
> cat text
Sed is a stream editor.
> sed "/stream/p" text
Sed is a stream editor.
Sed is a stream editor.
> sed -n "/stream/p" text
Sed is a stream editor.
2.3 地址
| 范例 | 含义 |
|---|---|
| n | 在第N行执行命令 |
| m,n | 在 m ~ n 行执行命令 |
| /RE/ | 匹配正则/RE/所在的行 |
| n,/RE/ | 从第n行到匹配正则表达式/RE/ 所在的行,如果 /RE/ 没有匹配,则从n到最后一行 |
| /RE/, m | 从/RE/到第m行,如果/RE/没有匹配则不会执行 |
| /RE1/, /RE2/ | 从/RE1/行到/RE2/行 |
2.4 命令
| 命令 | 含义 | 地址空间 |
|---|---|---|
| s | 内容替换 | 单地址,地址对 |
| d | 行删除 | 单地址,地址对 |
| c | 行替换 | 单地址,地址对 |
| p | 行打印 | 单地址,地址对 |
| a | 行追加 | 单地址 |
| i | 行插入 | 单地址 |
| = | 打印行号 | 单地址 |
NOTE: 单地址: 具体的地址。 地址对:地址范围,如m,n
2.5 栗子
Sed is a stream editor. A stream editor is used to perform basic
text transformations on an input stream (a file or input from a pipeline).
Whilein some ways similar to an editor which permits scripted edits (such as ed),
sed works by making only one pass over the input(s).
2.5.1 内容替换
[address]s/pattern/replace text/flags
sed -n "1,2 s/stream/strong stream/g" text
2.5.2 行替换
[address-pair | address]c\text 将匹配的行替换成text的内容。
sed "1,2c\Sed is a good editor." text
-------------------------------------
Sed is a good editor.
While in some ways similar to an editor which permits scripted edits (such as ed),
sed works by making only one pass over the input(s).
NOTE: 上述1,2两行替换成了一行内容。
2.5.3 行插入
[address]i\text 在指定行出插入text的内容
sed "1i\Sed is a good editor." text
-----------------------------------
Sed is a good editor.
Sed is a stream editor. A stream editor is used to perform basic
text transformations on an input stream (a file or input from a pipeline).
While in some ways similar to an editor which permits scripted edits (such as ed),
sed works by making only one pass over the input(s).
2.5.4 打印行号
查找/basic/ 所在的行,打印该行,并输出行号。{ } 命令集,通过;分割命令。
sed -n "/basic/{=;p}" text
---------------------------
1
Sed is a stream editor. A stream editor is used to perform basic
本文介绍了Linux系统中两个强大的文本处理工具Grep和Sed。Grep用于搜索文件中的特定模式,Sed则是一个流编辑器,通过按行处理文本并执行命令来实现文本变换。Sed的工作原理、参数、地址、命令以及各种用例,如内容替换、行替换、行插入和打印行号等,都在文中进行了详细讲解。
1201

被折叠的 条评论
为什么被折叠?



