首页 > 解决方案 > Bash 用 grep 提取字符串

问题描述

假设我在一个文件中有多个字符串,我只想提取一个特定的字符串

$plugin->component = 'mod_jitsi';
$plugin->component = 'local_hvp';
$plugin->component = 'test_bot';
$plugin->component = 'mod_bot';
$plugin->component = 'mod_moodle';

我想用 grep 过滤它,所以我的输出如下所示:

mod
local
test
mod
mod

有什么办法可以用 grep 做到这一点,还是我需要使用 awk 或 sed?

提前致谢!

标签: stringshellfiltergrep

解决方案


使用 GNUgrep和 pcre 正则表达式:

grep -Po "(?<== ')[^_]*" input.txt

(?<== ')是一个零宽度的正向后视断言。它不包含在匹配的文本中,但它必须与= '包含的 RE 部分之前匹配(即从引号之后到第一个下划线的所有内容。


推荐阅读