0

I'd like to split a string with BusyBox's awk using multiple and different characters. For example, spaces and slashes.

I read the answer of Can field separator in awk encompass multiple characters?. It states that you should be able to pass "even a regex" as separator. But I'm unable to find the right syntax:

It is this output line of ip which I'm working on:

inet 192.168.2.1/24 brd 192.168.2.255 scope global eth0                                       

I'd like to exact the IPv4 address:

ip -4 addr show dev eth0 | grep inet | awk -F'[ \/]' '{print $2;}'

But it doesn't work.

Community
  • 1
  • 1
Patrick B.
  • 11,773
  • 8
  • 58
  • 101

3 Answers3

2

Following code will check for the line containing a string "inet". If this matched, then the second column in split into an array named "a". and the first element of that array is printed.

ip -4 addr show dev eth0  |awk '/inet/{split($2,a,"/");print a[1]}'

Or you can try grep :

ip -4 addr show dev eth0 |grep -oP 'inet\s\K.*?[^/]+'
P....
  • 17,421
  • 2
  • 32
  • 52
0

When using a regex, one needs to specify how many characters to match for. My regex was missing that:

ip -4 addr show dev eth0 | awk -F"[ /]+" '/inet/{print $3}'

is working. (Note, I'm running the busybox-version of awk)

The +-operator stands for at least one of the character list needs to match.

I also could remove the grep, thanks @PS.

Patrick B.
  • 11,773
  • 8
  • 58
  • 101
  • Well, I just had to test it but on my Busybox at hand (Ubuntu 1:1.21.0-1ubuntu1) and that `+` was not needed. You (awk) code worked as-is. – James Brown Mar 14 '17 at 08:42
0

Use split:

$ awk '{split($2,a,"/");print a[1]}' foo
192.168.2.1
James Brown
  • 36,089
  • 7
  • 43
  • 59