正则表达式匹配唯一ID

时间:2021-06-15 01:26:11

I am writing a shell script that searches a text file for a pattern.

我正在编写一个shell脚本,在文本文件中搜索模式。

The pattern is: uid- and then an alphanumeric string containing only lower case letters and numbers. For example: uid-12ab34de

模式是:uid-然后是一个只包含小写字母和数字的字母数字字符串。例如:uid-12ab34de

#!/bin/bash
value=$(grep -R "^uid-[a-z][0-9]" "./text.txt")
echo "$value"

I have several attempts at this now and have come here as a last resort. Thanks for any help in advance!

我现在有几次尝试,并作为最后的手段来到这里。在此先感谢您的帮助!

2 个解决方案

#1


Use

#!/bin/bash
value=$(grep -R "^uid-[a-z0-9]+$" "./text.txt")
echo "$value"

Your regexp chose a single lowercase letter followed by a single digit. Moreover, it would have accepted strings that have a valid uid as a prefix only (i.e. ending in illegal/unsupported characters). The latter may have been intentional, if so drop the $.

你的正则表达式选择了一个小写字母后跟一个数字。此外,它将接受仅具有有效uid作为前缀的字符串(即以非法/不支持的字符结尾)。后者可能是有意的,如果这样下降$。

#2


Try this:

value=$(grep -ER "^uid-[a-z0-9]+" "./text.txt")

-E for using ERE (Extended Regular Expression)

-E用于使用ERE(扩展正则表达式)

You can do this too (for GNU grep) in BRE (Basic Regular Expression) mode:

您也可以在BRE(基本正则表达式)模式下执行此操作(对于GNU grep):

value=$(grep -R "^uid-[a-z0-9]\+" "./text.txt")

Or:

value=$(grep -R "^uid-[a-z0-9]\{1,\}" "./text.txt")

If you want portability with BRE, then:

如果您想要使用BRE进行移植,那么:

value=$(grep -R "^uid-[a-z0-9]*" "./text.txt")

But this will match even the id portion of the uid is empty (like uid-)

但这甚至匹配uid的id部分是空的(如uid-)

A little explanation:

一点解释:

+, \+ \{1,\} matches for at least one or more occurrences of the precedent regex.

+,\ + \ {1,\}匹配至少一次或多次出现的先例正则表达式。

* matches zero or more occurrences of the precedent regex.

*匹配先前正则表达式的零次或多次出现。

#1


Use

#!/bin/bash
value=$(grep -R "^uid-[a-z0-9]+$" "./text.txt")
echo "$value"

Your regexp chose a single lowercase letter followed by a single digit. Moreover, it would have accepted strings that have a valid uid as a prefix only (i.e. ending in illegal/unsupported characters). The latter may have been intentional, if so drop the $.

你的正则表达式选择了一个小写字母后跟一个数字。此外,它将接受仅具有有效uid作为前缀的字符串(即以非法/不支持的字符结尾)。后者可能是有意的,如果这样下降$。

#2


Try this:

value=$(grep -ER "^uid-[a-z0-9]+" "./text.txt")

-E for using ERE (Extended Regular Expression)

-E用于使用ERE(扩展正则表达式)

You can do this too (for GNU grep) in BRE (Basic Regular Expression) mode:

您也可以在BRE(基本正则表达式)模式下执行此操作(对于GNU grep):

value=$(grep -R "^uid-[a-z0-9]\+" "./text.txt")

Or:

value=$(grep -R "^uid-[a-z0-9]\{1,\}" "./text.txt")

If you want portability with BRE, then:

如果您想要使用BRE进行移植,那么:

value=$(grep -R "^uid-[a-z0-9]*" "./text.txt")

But this will match even the id portion of the uid is empty (like uid-)

但这甚至匹配uid的id部分是空的(如uid-)

A little explanation:

一点解释:

+, \+ \{1,\} matches for at least one or more occurrences of the precedent regex.

+,\ + \ {1,\}匹配至少一次或多次出现的先例正则表达式。

* matches zero or more occurrences of the precedent regex.

*匹配先前正则表达式的零次或多次出现。