如何在bash中匹配此字符串?(How to match this string in bash?)

编程入门 行业动态 更新时间:2024-10-24 06:36:17
如何在bash中匹配此字符串?(How to match this string in bash?)

我正在逐行读取bash中的文件。 我需要打印具有以下格式的行:

不在乎<<<至少有一个人物>>>不在乎。

这些都是我尝试过的方式,但没有一个能够工作:

if [[ $line =~ .*<<<.+>>>.* ]]; then echo "$line" fi

这有不正确的语法

这两个有正确的语法不起作用

if [[ $line =~ '.*<<<.+>>>.*' ]]; then echo "$line" fi

还有这个:

if [[ $line == '*<<<*>>>*' ]]; then echo "$line" fi

那么如何告诉bash只打印那种格式的行? PD:我已测试并打印所有线路工作正常。

I'm reading a file in bash, line by line. I need to print lines that have the following format:

don't care <<< at least one character >>> don't care.

These are all the way which I have tried and none of them work:

if [[ $line =~ .*<<<.+>>>.* ]]; then echo "$line" fi

This has incorrect syntax

These two have correct syntax don't work

if [[ $line =~ '.*<<<.+>>>.*' ]]; then echo "$line" fi

And this:

if [[ $line == '*<<<*>>>*' ]]; then echo "$line" fi

So how to I tell bash to only print lines with that format? PD: I have tested and printing all lines works just fine.

最满意答案

为了获得最大的兼容性,将单个引号中的正则表达式模式定义为单独的变量始终是一个好主意,然后使用它不加引号。 这对我有用:

re='<<<.+>>>' if [[ $line =~ $re ]]; then echo "$line" fi

顺便说一下,我摆脱了多余的领先/尾随.* 。

当然,我假设您有正当理由以原生bash处理文件(如果没有,只需使用grep -E '<<<.+>>>' file )

For maximum compatibility, it's always a good idea to define your regex pattern as a separate variable in single quotes, then use it unquoted. This works for me:

re='<<<.+>>>' if [[ $line =~ $re ]]; then echo "$line" fi

I got rid of the redundant leading/trailing .*, by the way.

Of course, I'm assuming that you have a valid reason to process the file in native bash (if not, just use grep -E '<<<.+>>>' file)

更多推荐

本文发布于:2023-08-07 12:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464222.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   如何在   string   bash   match

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!