在bash中,如何检索以特定表达式开头的字符串? [英] In bash, how to retrieve string starting with a specific expression?

查看:40
本文介绍了在bash中,如何检索以特定表达式开头的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出此文件:

a=as/dsdf b=fdfsf c=vcv
c=15 b=1 a=azzzz))]ee
a=12 z=19 r=15

我只想检索以 a =

因此在这种情况下的输出将是:

so the output in this case would be:

a=as/dsdf
a=azzzz))]ee
a=12

我已经深入研究bash文档,但找不到任何简单的方法,您有什么建议吗?

I've dived into bash documentation but couldn't find anything easy, do you have any suggestion ?

谢谢

推荐答案

我假设您希望以 a = 开头的所有内容都扩展到下一个空格.

I'm assuming that you want everything starting with a= up to the next space.

并非所有版本的grep都支持,但是如果您有 -o 选项,这很简单:

It's not supported by all versions of grep but if you have the -o option this is easy:

grep -Eo 'a=[^ ]+' file

-o 打印该行的匹配部分. -E 启用 扩展>正则表达式,使您可以使用 + 来表示一个或多个前一个 atom *的出现. [^] 表示空格以外的任何字符.

-o prints the matching part of the line. -E enables Extended Regular Expressions, which enables you to use + to mean one or more occurrences of the preceding atom*. [^ ] means any character other than a space.

否则,请使用sed捕获您感兴趣的零件:

Otherwise, use sed to capture the part you're interested in:

sed -E 's/.*(a=[^ ]+).*/\1/' file

作为万不得已的方法,如果您的sed版本不支持扩展的正则表达式,则该版本应适用于任何版本:

As a last resort, if your version of sed doesn't support extended regexes, this should work on any version:

sed 's/.*\(a=[^ ]\{1,\}\).*/\1/' file

正如注释中正确指出的(谢谢)一样,为避免打印不匹配的行,您可能还想使用 -n 来抑制输出并添加 p 命令以打印匹配的行:

As rightly pointed out in the comments (thanks), to avoid printing lines that don't match, you may also want to use -n to suppress output and add a p command to print lines that match:

sed -nE 's/.*(a=[^ ]+).*/\1/p' file


atom *:字符类,标记的子表达式或单个字符.


atom* : A character class, a marked sub-expression or a single character.

这篇关于在bash中,如何检索以特定表达式开头的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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