Tai Nguyen
Tai Nguyen

Reputation: 115

How to split multi-formatted lines

I'm having a problem in splitting multi-formatted lines. I want to get all the gateway from command route -n. All I know is using cut, but it doesn't work.

Assume that my route -n shows the following message:

Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.12.2    0.0.0.0         UG    0      0        0 eth0
0.0.0.0         192.168.12.1    0.0.0.0         UG    1024   0        0 eth0

I want to get: 192.168.12.2 and 192.168.12.1

Upvotes: 2

Views: 48

Answers (3)

spectre007
spectre007

Reputation: 1539

If you want to use the cut command, you can do it this way:

route -n | tr -s " " | cut -d" " -f2 | grep "[0-9]"

Note: Here the second column is the gateway IP address column (in numbers) in "route -n" command output.

Upvotes: 1

amdixon
amdixon

Reputation: 3833

File process.awk

#!/usr/bin/awk -f

{                              \
  if(FNR > 1)                  \
  {                            \
    printf $2"\n";             \
  }                            \
}                              \

Sample input.txt

Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.12.2    0.0.0.0         UG    0      0        0 eth0
0.0.0.0         192.168.12.1    0.0.0.0         UG    1024   0        0 eth0

Output

$ ./process.awk input.txt
192.168.12.2
192.168.12.1

Upvotes: 1

Cyrus
Cyrus

Reputation: 88601

route -n | awk 'FNR > 1 {print $2}'

Output:

192.168.12.2
192.168.12.1

Upvotes: 1

Related Questions