1
VAR="10.101.10.5"

I have a text file abc.txt in the below format:

Name : www.ayz.com  { Destination : 10.101.10.2  tcpmask        members {     10.101.10.5 :http { address 10.101.10.5 }  10.101.10.3 :http { address 10.101.10.3 } } 

Name : www.abc.com   { Destination : 10.101.10.5  tcpmask        members {     10.101.10.5 :http { address 10.101.10.5 }  10.101.10.3 :http { address 10.101.10.3 } } 

The requirement is when I grep for a specific IP for example 10.101.10.5. It should the search only the line which has the IP 10.101.10.5 after the word Destination and before the word members.

So basically I need a command which just lists the second line only when I grep for 10.101.10.5, it should not return first line because it has IP after members.

I tried using sed but it's not helping:

sed -n '/destination : $VAR /,/<members>/p' /abc.txt
Cyrus
  • 84,225
  • 14
  • 89
  • 153
Manish
  • 35
  • 1
  • 5
  • Can’t you just do `grep 'Destination : 10.101.10.5' abc.txt`? – cmbuckley Apr 25 '20 at 20:20
  • 1
    [Typing your question into google](https://www.google.com/search?q=Extract+Specific+word+from+Text+file+between+Specifc+words+in+BASH) it just follows to [this thread](https://stackoverflow.com/questions/13242469/how-to-use-sed-grep-to-extract-text-between-two-words). Please make sure you posted the files properly formatted, I think your post indicates that the `Name:` and `Destination:` are on different lines in the input files, yet in your post they are on the same line. – KamilCuk Apr 25 '20 at 20:21
  • Sorry I forgot to mention in my question I have 10.101.10.5 in Variable like VAR="10.101.10.5" so if I am using grep 'Destination : $VAR' abc.txt it is not returning result – Manish Apr 25 '20 at 20:32

2 Answers2

1

I suggest:

grep 'Destination .* 10\.101\.10\.5 .* members' abc.txt

Update:

grep "Destination .* ${VAR//./\\.} .* members" abc.txt

See: Difference between single and double quotes in bash

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • The Problem with this is I am Keeeping 10.101.10.5 value in another Variable like this VAR="10.101.10.5" so if use your command : grep 'Destination . $VAR.* members' abc.txt ..it will not work – Manish Apr 25 '20 at 20:29
1

Use double quotas and variable name. You can use also some regexp, for example grep "Destination\s*:\s*$VAR" to be more flexible for extra spaces after Destination

$ VAR="10.101.10.5"
$ grep "Destination : $VAR" file.txt
Name : www.abc.com   { Destination : 10.101.10.5  tcpmask        members {     10.101.10.5 :http { address 10.101.10.5 }  10.101.10.3 :http { address 10.101.10.3 } }
Saboteur
  • 1,331
  • 5
  • 12