简体   繁体   English

如何在bash中使用正则表达式在双引号之间选择字符串?

[英]How to use regex in bash for selecting a string between double quotes?

I really searched this kind of question among the other similar questions here but couldn't find any answer. 我真的在这里的其他类似问题中搜索了这种问题,但找不到任何答案。

I have the following text in a file: 我的文件中包含以下文本:

TYPE_A = "1" AND TYPE_B = "6" AND TYPE_C = "8755asd-"

I am trying to grep the following (the double quotes can include numbers, characters and special characters): 我正在尝试grep以下内容(双引号可以包含数字,字符和特殊字符):

TYPE_C = "8755asd-"

The grep command that I am using is this: grep -o "TYPE_C = \\"[0-9a-zA-Z-]*\\"" text.txt 我正在使用的grep命令是这样的: grep -o "TYPE_C = \\"[0-9a-zA-Z-]*\\"" text.txt

However, I think the regex in this command is not generic. 但是,我认为此命令中的正则表达式不是通用的。

Thank you for your help. 谢谢您的帮助。

You could use the below regex which matches the corresponding TYPE only if the double quotes contain all the characters you mentioned . 你可以使用它匹配相应的正则表达式如下TYPE只有在双引号包含你所提到的所有字符。 That is, atleast a character, atleast a number, atleast a special character. 即,至少一个字符,至少一个数字,至少一个特殊字符。

grep -oP 'TYPE_[A-Z]\s*=\s*"(?=[^"]*[A-Za-z])(?=[^"]*\d)(?=[^"]*[^"\w])[\W\w]*?"' file

DEMO 演示

Example: 例:

$ cat ri
TYPE_A = "1" AND TYPE_B = "6" AND TYPE_C = "8755asd-"
TYPE_A = "1" AND TYPE_B = "6" AND TYPE_C = "875d"
TYPE_A = "1" AND TYPE_B = "6" AND TYPE_C = "asd-"
TYPE_A = "1" AND TYPE_B = "6" AND TYPE_C = "875-"
$ grep -oP 'TYPE_[A-Z]\s*=\s*"(?=[^"]*[A-Za-z])(?=[^"]*\d)(?=[^"]*[^"\w])[\W\w]*?"' ri
TYPE_C = "8755asd-"

I'd do it with sed : 我会用sed来做的:

sed -n 's@.* TYPE_C = "\([0-9a-zA-Z-]*\)".*@\1@p' text.txt

That is, -n to not print lines that don't match. 也就是说, -n不打印不匹配的行。 Then replace the entire line with the part in double quotes after TYPE_C, and p to print the result: 然后用TYPE_C后的双引号替换整个行,并使用p打印结果:

8755asd-

如果模式保持不变,则可以使用cut获得相同的输出。

echo 'TYPE_A = "1" AND TYPE_B = "6" AND TYPE_C = "8755asd-"' | cut -d"\"" -f6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM