Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse interfaces from ifconfig

Tags:

regex

grep

sed

I'm trying to get the list of networks interfaces from the command-line in this form:

"wlan0","eth0","lo"

I don't need to get them in a special order.

I can do this:

wlan0,eth0,lo

with this super non-optimized command, after having searched a lot and after I think I've reached my limits:

ifconfig -a | grep -E '' | sed -n 's/^\([^ ]\+\).*/\1/p' | tr -d '\n' | sed s/:/,/g | sed 's/.$//' 
like image 607
sidney Avatar asked Dec 08 '22 20:12

sidney


2 Answers

I'll add this one to the pile. Add the quotes in the first sed, then just join the lines with paste.

ifconfig -a | sed -n 's/^\([^ ]\+\).*/"\1"/p' | paste -sd ","

This is better than tr since there's no trailing comma.

Better yet, since ifconfig -a output can't really be counted on to stay consistent, check /sys/class/net

ls /sys/class/net | sed -e 's/^\(.*\)$/"\1"/' | paste -sd ","
like image 150
Tom McClure Avatar answered Feb 15 '23 16:02

Tom McClure


How about:

ifconfig -a | sed -e '/^ /d;/^$/d;s/\([^ ]*\) .*/"\1"/' | tr '\n' ','

There are three commands we're executing:

  1. /^ /d this command checks if the line starts with a space. If it does, "d" deletes it (and goes to the next line without executing the remaining commands).
  2. /^$/d this command deletes empty lines
  3. s/\([^ ]*\) .*/"\1"/ this command is reached when the above commands fail (ie., now we have a line that isn't empty and doesn't start with a space). What it does is capture as much characters that aren't spaces as it can, and then matches all characters from the space to the end of the line. The replacement string contains the special \1 "variable", which contains the captured string (ie. the interface name). We also include it between quotes.

After the sed command, we have the interfaces between double quotes, but one per line. To fix this we use tr '\n' ',' to replace newline characters with commas.

Hope this helps =)

like image 23
Janito Vaqueiro Ferreira Filho Avatar answered Feb 15 '23 17:02

Janito Vaqueiro Ferreira Filho