如何将正则表达式的匹配项分配给变量? [英] How can I assign the match of my regular expression to a variable?

查看:62
本文介绍了如何将正则表达式的匹配项分配给变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有各种条目的文本文件.每个条目都以包含所有星号的行结尾.

I have a text file with various entries in it. Each entry is ended with line containing all asterisks.

我想使用shell命令来解析该文件并将每个条目分配给一个变量.我该怎么办?

I'd like to use shell commands to parse this file and assign each entry to a variable. How can I do this?

这是一个示例输入文件:

Here's an example input file:


***********
Field1
***********
Lorem ipsum
Data to match
***********
More data
Still more data
***********

这是到目前为止我的解决方案:

Here is what my solution looks like so far:

#!/bin/bash
for error in `python example.py | sed -n '/.*/,/^\**$/p'`
do
    echo -e $error
    echo -e "\n"
done

但是,这只是将匹配文本中的每个单词分配给$ error,而不是整个块.

However, this just assigns each word in the matched text to $error, rather than a whole block.

推荐答案

我很惊讶在这里没有看到本地的bash解决方案.是的,bash具有正则表达式.您可以在网上找到大量随机文档,特别是如果您在查询中包含"bash_rematch",或者仅查看手册页.这是一个愚蠢的示例,摘自此处,并稍加修改,即可显示整个匹配项,以及捕获的每个匹配项,以获取正则表达式.

I'm surprised to not see a native bash solution here. Yes, bash has regular expressions. You can find plenty of random documentation online, particularly if you include "bash_rematch" in your query, or just look at the man pages. Here's a silly example, taken from here and slightly modified, which prints the whole match, and each of the captured matches, for a regular expression.

if [[ $str =~ $regex ]]; then
    echo "$str matches"
    echo "matching substring: ${BASH_REMATCH[0]}"
    i=1
    n=${#BASH_REMATCH[*]}
    while [[ $i -lt $n ]]
    do
        echo "  capture[$i]: ${BASH_REMATCH[$i]}"
        let i++
    done
else
    echo "$str does not match"
fi

重要的一点是扩展测试 [[... ...]] 使用其正则表达式比较 =〜将整个匹配项存储在 $ {BASH_REMATCH [0]} 和捕获的匹配项在 $ {BASH_REMATCH [i]} 中.

The important bit is that the extended test [[ ... ]] using its regex comparision =~ stores the entire match in ${BASH_REMATCH[0]} and the captured matches in ${BASH_REMATCH[i]}.

这篇关于如何将正则表达式的匹配项分配给变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆