1

This is the text that I have

Peer Addr 1.1.1.1, Intf Port-Channel0.1, State Up
VRF default, LAddr 1.1.1.1, LD/RD 090/592
Session state is Up and using echo function with 300 ms interval
Detect Time: 8000
Sched Delay: 1*TxInt: 3522100, 2*TxInt: 5, 3*TxInt: 0, GT 3*TxInt: 0
Registered protocols: isis bgp ospf

I want the values after Peer Addr, Intf and Registered protocols

Expected output

1.1.1.1 

Port-Channel0.1

isis bgp ospf

This is what I have tried

grep -oP "Peer Addr\s+\K\w+"

I am unable to get the required output. I am new to shell scripting and would be great if someone can help me out on this one. I don't want all the output in a single command. I would like to store these as three different variables

  • `grep -Po 'Peer Addr \K.*?(?=,)' file`? – Cyrus Jul 11 '16 at 04:36
  • 1
    Possible duplicate of [linux: Extract one word after a specific word on the same line](http://stackoverflow.com/questions/17371197/linux-extract-one-word-after-a-specific-word-on-the-same-line) – tripleee Jul 11 '16 at 06:07

4 Answers4

2

With GNU awk for multi-char RS:

$ awk -v RS='[\n,]\\s*' 'sub(/^(Peer Addr|Intf|Registered protocols:) /,"")' file
1.1.1.1
Port-Channel0.1
isis bgp ospf
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
2

With GNU grep:

grep -Po '(Peer Addr|Intf|protocols:) \K.*?(?=(,|$))' file

Output:

1.1.1.1
Port-Channel0.1
isis bgp ospf

-P PATTERN: Interpret PATTERN as a Perl regular expression.

-o: Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

\K: If \K appears in a Perl regex, it causes the regex matcher to drop everything before that point.

(?=...): The captured match must be followed by , or end of line ($) but that part is dropped, too.

Community
  • 1
  • 1
Cyrus
  • 84,225
  • 14
  • 89
  • 153
0

With sed, you could do something like this:

sed -rn 's/Peer Addr *([^,]+), */\1/;
         s/Intf *([^,]+),.*/\n\1/;
         s/Registered protocols: *//;
         ta;d;:a p' 
Michael Vehrs
  • 3,293
  • 11
  • 10
0
awk -F"[, ]" '/^Peer Addr/{print $3"\n"$6} /^Registered protocols:/{sub(/Registered protocols: /,"");print}' File

Here IFS as , and .

/^Peer Addr/{print $3"\n"$6} : If a line starts with Peer Addr print $3( Here 1.1.1.1) and $6( Port-Channel0.1).

/^Registered protocols:/{sub(/Registered protocols: /,"");print}': If a line starts with Registered protocols: print entire line after removing the string Registered protocols: with sub awk function.

jijinp
  • 2,592
  • 1
  • 13
  • 15
  • Could you explain how your answer works? As-is, it may do what the OP wants, but they may not find it very informative. – Yossarian Jul 11 '16 at 10:35
  • Although this code may be help to solve the problem, providing additional context regarding _why_ and/or _how_ it answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – Toby Speight Jul 11 '16 at 12:53