How to use grep to extract a substring?

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

Here is my command:

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

It outputs:

  • FIN (SUCCESS)

And I would like it to output only:

SUCCESS

How can I tell grep to do this?

+4
source share
3 answers

You can pass the output of grep to awk.

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

I'm not sure how to do this with grep alone, as it is not suitable for this particular use case. Since you are on a platform with grep, use the pipes to your advantage when you can have one team to solve part of the problem and another team in the other part.

+4
source

grep cannot output one capture group, but you can use sed to do this:

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

If you use ack , you can use matching groups and the --output switch:

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

Source: https://habr.com/ru/post/1435972/


All Articles