如何使用grep提取子字符串? [重复]

时间:2021-01-07 19:16:58

Possible Duplicate:
extract regexp result from string and write it to a variable

可能重复:从字符串中提取regexp结果并将其写入变量

Here is my command :

这是我的命令:

grep -E '\*[[:space:]]+FIN[[:space:]]+([^)]+?)') myfile

grep -E'\ * [[:space:]] + FIN [[:space:]] +([^]] +?)')myfile

It outputs :

它输出:

  • FIN (SUCCESS)

And I would like it outputs only :

而且我希望它仅输出:

SUCCESS

How can I tell grep to do it ?

我该如何告诉grep这样做?

3 个解决方案

#1


5  

You can pipe the output of your grep command to the awk command.

您可以将grep命令的输出通过管道传递给awk命令。

grep -E '*[[:space:]]+FIN[[:space:]]+([^)]+?)') myfile | awk '{print $2}'

I am not sure how to do that with grep alone, as it is not really tailored to that exact use case. Since you are on a platform where grep is, use pipes to your advantage when you can have one command solve part of the problem, and another command the other part.

我不确定如何单独使用grep,因为它不是真正适合那个确切的用例。由于您位于grep所在的平台上,因此当您可以使用一个命令解决部分问题时使用管道,而另一个命令则使用另一个部分。

#2


3  

grep is not capable of outputting a single capture group, but you can use sed to do it instead:

grep无法输出单个捕获组,但您可以使用sed来代替:

sed 's/\*[[:space:]]\+FIN[[:space:]]\+(\([^)]\+\))/\1/g' file

#3


2  

If you use ack then you can use match groups and the --output switch:

如果你使用ack,那么你可以使用匹配组和--output开关:

ack '\*\s+FIN\((.+?)\)' --output='$1' myfile

#1


5  

You can pipe the output of your grep command to the awk command.

您可以将grep命令的输出通过管道传递给awk命令。

grep -E '*[[:space:]]+FIN[[:space:]]+([^)]+?)') myfile | awk '{print $2}'

I am not sure how to do that with grep alone, as it is not really tailored to that exact use case. Since you are on a platform where grep is, use pipes to your advantage when you can have one command solve part of the problem, and another command the other part.

我不确定如何单独使用grep,因为它不是真正适合那个确切的用例。由于您位于grep所在的平台上,因此当您可以使用一个命令解决部分问题时使用管道,而另一个命令则使用另一个部分。

#2


3  

grep is not capable of outputting a single capture group, but you can use sed to do it instead:

grep无法输出单个捕获组,但您可以使用sed来代替:

sed 's/\*[[:space:]]\+FIN[[:space:]]\+(\([^)]\+\))/\1/g' file

#3


2  

If you use ack then you can use match groups and the --output switch:

如果你使用ack,那么你可以使用匹配组和--output开关:

ack '\*\s+FIN\((.+?)\)' --output='$1' myfile