如何正确使用bash中的正则表达式捕获组? [英] How to use regex capturing group in bash correctly?

查看:77
本文介绍了如何正确使用bash中的正则表达式捕获组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将一些字符串加载到变量结果"中.字符串如下所示:

I've loaded some strings into variable "result". The strings look like this:

school/proj_1/file1.txt
school/proj_1/file2.txt
school/proj_1/file3.txt

我尝试仅获取最后一个斜杠后的名称,因此file1.txt,file2.txt和file3.txt是我想要的结果.我使用这段代码

I try to get only the name after the last slash, so file1.txt, file2.txt and file3.txt is the desirable result for me. I use this piece of code

for i in $result
do
  grep "school/proj_1/(.*)" $i
done

但是它不起作用.我觉得该正则表达式可与我创建的caputuring组一起在Python上使用,但是我无法真正解决如何在bash中使用捕获组,甚至根本不可能的事情.

but it doesn't work. I feel that the regex would work for Python with the caputuring group I created, but I can't really wrap my head around how to use capturing groups in bash or if it is even possible at all.

很抱歉,这是一个愚蠢的问题,我对使用bash编写脚本非常陌生.

I'm sorry if it's a dumb question, I'm very new to scripting in bash.

推荐答案

您可以对字符串处理操作:

echo "${i##*/}"

$ {string ## substring}
  从 $ string front 删除 $ substring 的最长匹配项

${string##substring}
  Deletes longest match of $substring from front of $string.

或者在Bash中使用正则表达式,您可能会获得类似的捕获组

Or using a regex in Bash, you may get the capturing groups like

result=("school/proj_1/file1.txt" "school/proj_1/file2.txt" "school/proj_1/file3.txt")
rx='school/proj_1/(.*)'
for i in "${result[@]}"; do
    if [[ "$i" =~ $rx ]]; then
        echo "${BASH_REMATCH[1]}"
    fi
done

请参见在线演示.在这里, $ {BASH_REMATCH [1]} 是捕获组#1中的内容.

See the online demo. Here, ${BASH_REMATCH[1]} is the contents inside capturing group #1.

这篇关于如何正确使用bash中的正则表达式捕获组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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