【问题标题】:Run Regex using Grep/Sed recursively over files to store capture group使用 Grep/Sed 在文件上递归运行 Regex 以存储捕获组
【发布时间】:2019-10-25 19:20:45
【问题描述】:

我的文件结构如下:

  • 文件夹 1
    • file1.feature
    • file2.feature
    • file3.feature
  • 文件夹 2
    • file1.feature
    • file2.feature
    • ...等

这些文件是 Behat 功能文件,如下所示:

Scenario: I am filling out a form
    Given I am logged in as User
    And I fill in "Name" with "My name"
    Then I fill in "Email" with "myemail@example.com"

我正在尝试遍历文件结构中的每个文件以匹配我的正则表达式:

/I fill in "[^"]+" with "([^"]+)"/gm

正则表达式查找我用“y”填充“x”,并且我想从文件中的一行与表达式匹配的每个文件中存储捕获组“y”。

到目前为止,我可以遍历文件夹并在 mt Bash 脚本中打印出文件名,如下所示:

#!/bin/bash

cd behat/features

files="*/*.feature"


for f in $files
do
    echo ${f}
done

我正在尝试通过在我的循环中执行此操作来检索当前使用 Sed 的捕获组:

sed -r 's/^I fill in \"[^)]+\" with \"([^)]+)\"$/\1/'

但我担心我会走错路,因为这会返回所有文件中的所有文件内容。

【问题讨论】:

  • 试试sed -E -n 's/.*I fill in "[^"]+" with "([^"]+)"/\1/p',见this demo
  • @WiktorStribiżew sweet,当我在单个文件上运行它时,它可以工作,你知道我如何将它合并到我的脚本中吗?
  • cd behat/features && find . -name *.feature -type f -print0 | xargs -0 sed -E -n 's/.*I fill in "[^"]+" with "([^"]+)"/\1/p' > outfile?
  • @WiktorStribiżew 老兄,谢谢!!将其发布为答案,我可以接受。

标签: regex bash sed grep


【解决方案1】:

你可以使用

cd behat/features && find . -name *.feature -type f -print0 | xargs -0 \
  sed -E -n 's/.*I fill in "[^"]+" with "([^"]+)"/\1/p' > outfile

此命令“转到”behat/features 目录,查找所有带有feature 扩展名的文件(递归),然后打印与您的正则表达式匹配的捕获组#1 值,因为-n 选项抑制行的输出和@ 987654326@ 标志仅输出替换后剩余的内容。

如果需要,请在How to do a recursive find/replace of a string with awk or sed? 上查看更具体的递归文件匹配解决方案。

【讨论】:

    猜你喜欢
    • 2010-12-25
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多