You are not logged in.

#1 2012-02-06 21:18:36

oliver
Member
Registered: 2007-12-12
Posts: 448

[solved] best way to extract text but only when it contains xyz

I have a file that looks like this:

<lots of config lines that aren't network related>
network-interface
  name eth0
  ip 192.168.100.43
  dns-timeout 11
  last-modified-by
network-interface
  name eth1
  ip 192.168.100.44
  dns-timeout 11
  last-modified-by
network-interface
  name eth2
  ip 10.10.10.10
  dns-timeout 5
  last-modified-by
<lots of config lines that aren't network related>

I can use awk to extract just the network-interfaces (something like: awk '/^network-interface/,/last-modified-by/' <file>) but it prints out all three interfaces and I only want to see it if it contains the name 'eth2' (and I do need the whole block)

Doesn't have to be awk, can be anything within reason (sed/perl/python/awk/bash)

What would be the most elegant way to do this?

The finished output should look like this:

network-interface
  name eth2
  ip 10.10.10.10
  dns-timeout 5
  last-modified-by

Last edited by oliver (2012-02-07 14:37:00)

Offline

#2 2012-02-06 21:29:18

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: [solved] best way to extract text but only when it contains xyz

Try grep:

[karol@black ~]$ grep -B1 -A4 eth2 <somefilename>
network-interface
  name eth2
  ip 10.10.10.10
  dns-timeout 5
  last-modified-by

Edit: Fixed.

Last edited by karol (2012-02-06 21:31:40)

Offline

#3 2012-02-06 21:36:28

oliver
Member
Registered: 2007-12-12
Posts: 448

Re: [solved] best way to extract text but only when it contains xyz

thanks... that does indeed work.

Offline

#4 2012-02-07 01:06:39

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,111
Website

Re: [solved] best way to extract text but only when it contains xyz

If you want something a little more generic, this won't retain the ordering of the keys, but it's not suspect to breaking when the number of keys changes:

#!/bin/bash

exec awk -v "eth=$1" '
/^network-interface/ {
  if (iface["name"] && iface["name"] == eth) {
    print
    for(k in iface) {
      print "  ", k, iface[k]
    }
    exit
  }
  delete iface
  next
}

{ iface[$1] = $2 }'

Execute something like:
./find-iface eth1 <file

Offline

#5 2012-02-07 01:45:34

oliver
Member
Registered: 2007-12-12
Posts: 448

Re: [solved] best way to extract text but only when it contains xyz

nice - thanks for posting

Offline

Board footer

Powered by FluxBB