Can I split on two characters, running awk only once?
Actually the field separator you define usung -F
is a regular expression. Thus the following command should deliver:
ip a | awk -F'[ /]+' '/inet / {print $3}'
ip a | awk '/inet / {FS="/"; $0=$2; print $1; FS=" "}'
The first matching record is split into fields according to the default FS
(space). Then a new FS
is set. When we substitute $0=$2
, splitting is done again according to the new FS
. Now $1
contains what we want, we print it. Finally we set FS
for the next matching record.
For this very specific case, have you considered a better use of ip
? For example:
ip -j -p -f inet a | awk -F \" '/local/ {print $4}'
This will print ip address
as a JSON object an search for the local
key, which happens to store the IP address. Is is even sharper you can use jq
:
ip -j -p -f inet a | jq '.[].addr_info[].local'
I recommend this last command as it will not suffer from changes in ip addr
output. However, if you really like your initial design, I would go with:
ip a | awk '/inet / {print substr($2, 1, index($2,"/")-1)}'
or
ip a | awk '/inet / {split($2, addr, "/"); print addr[1]}'
In the first command, we use index($2, "/")
to find where /
is in $2
and then use substr
to generate the substring. In the seconds one, we split $2
on /
and store it on addr
array.