【问题标题】:Bash extract string with grepBash 用 grep 提取字符串
【发布时间】:2023-03-20 06:07:01
【问题描述】:

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

$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?

提前致谢!

【问题讨论】:

  • $plugin->component = 是否在所有行中都保持不变,并且您想提取字符串其余部分中直到第一个 _ 的所有内容?
  • awk 无论如何都更清楚:awk -F "['_]" '{print $2}' file

标签: string shell filter grep


【解决方案1】:
echo '$plugin->component = 'mod_jitsi';
$plugin->component = 'local_hvp';
$plugin->component = 'test_bot';
$plugin->component = 'mod_bot';
$plugin->component = 'mod_moodle';' > STRING

awk 'BEGIN { FS ="=" } ; { print $2 }' STRING | cut -d "_" -f1



mod
local
test
mod
mod

【讨论】:

    【解决方案2】:

    使用 GNU grep 和 pcre 正则表达式:

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

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

    【讨论】:

      【解决方案3】:

      如果您的grep 支持与 Perl 兼容的正则表达式 (PCRE):

      grep -Po '\$plugin->component = '\''\K[^_]+' file
      

      sed:

      sed -En 's/\$plugin->component = '\''([^_]+).*/\1/p' file
      

      【讨论】:

        【解决方案4】:

        PCRE 可能是最好的方法,您已经有两个答案可以演示如何使用它。

        然而,还有一种更“基本”的方式——只使用 BRE(基本的正则表达式,由普通的grep 使用)。你只需要调用它两次。

        我假设每个输入行(最多)有一个由单引号组成的子字符串,后跟零个或多个非单引号、非下划线字符,后跟一个下划线,您必须提取此子字符串中的非单引号、非下划线字符。

        如果输入字符串在文件my_file中:

        [mathguy@localhost ~/test]$ more my_file
        $plugin->component = 'mod_jitsi';
        $plugin->component = 'local_hvp';
        $plugin->component = 'test_bot';
        $plugin->component = 'mod_bot';
        $plugin->component = 'mod_moodle';
        
        
        [mathguy@localhost ~/test]$ grep -o "'[^'_]*_" my_file | grep -o "[^'_]*"
        mod
        local
        test
        mod
        mod
        

        【讨论】:

          猜你喜欢
          • 2022-10-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-17
          • 2021-10-12
          • 2015-06-14
          • 2012-07-06
          • 2011-09-16
          相关资源
          最近更新 更多