rachuism rachuism - 8 months ago 50
Linux Question

How to extract a string from between two patterns in bash

Im begining with bash and I want to find my ip in a .txt file analyzing it.
This is an example of part of the file:
"Direc. inet:192.****** Difus.:"

The path I think on is searching all the text between "inet:" and " ". My biggest approach until now is getting the entire line with "grep inet:" but I can't figure out how to get just the ip not the entire line with the ip.

Thank you!


Since you're on Linux, you can take advantage of GNU grep's -o and -P options:

grep -oP '(?<= inet:)[^ ]+' file.txt


$ grep -oP '(?<= inet:)[^ ]+' <<<'Direc. inet:192.****** Difus.:'
  • -o tells grep to only output the matching part(s) of each line.

  • -P activates support for PCREs (Perl-compatible regular expressions), which support look-behind assertions such as (?<= inet:), which allow a sub-expression (inet:, in this case) to participate in matching, without being captured (returned) as part of the matched string.

  • [^ ]+ then simply captures everything after inet: up to the first space char. (character set [^ ] matches any char. that is not (^) a space, and + matches this set 1 or more times).