Reputation: 2625
I have a text mytest.txt
file whose content is
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:50:56:a6:4c:35", ATTR{type}=="1", PROGRAM="/lib/udev/rename_device", NAME="eth0"
I want to extract the mac address and nic name from the above. I have a very crude way of doing it. Here is what I am doing. Running cat
and awk
twice. I am wondering what is a better way of doing this. Also, if there were 2 lines in the file how would I do for both.
grep address mytest.txt|awk '{print $4}'
Output
ATTR{address}=="00:50:56:a6:4c:35",
grep address mytest.txt|awk '{print $7}'
Output
NAME="eth0",
How can I do it in a better way where I get the MAC address and name just separated by space. And also, if there are 2 lines in the file, get 2 lines in the output along the lines of
<mac1> <nic_name1>
<mac2> <nic_name2>
Upvotes: 0
Views: 171
Reputation: 4004
awk -F'"' '{print $8,$(NF-1)}' mytest.awk
This uses double-quotes mark as delimiter and prints the 8th and the second last fields, the latter retrieved by $(NF-1)
. NF
is an awk built-in that contains the number of fields of the current line, so $NF
is the last field and $(NF-1)
is the second last field.
Sample output:
$ cat file
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:50:56:a6:4c:35", ATTR{type}=="1", PROGRAM="/lib/udev/rename_device", NAME="eth0"
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="10:50:56:a6:4c:35", ATTR{type}=="1", PROGRAM="/lib/udev/rename_device", NAME="eth1"
$ awk -F'"' '{print $8,$(NF-1)}' file
00:50:56:a6:4c:35 eth0
10:50:56:a6:4c:35 eth1
Upvotes: 1
Reputation: 785876
You may use this awk
:
awk -F ',[ \t]*' '{gsub(/(^| )[^=]+=+|"/, ""); print $4, $NF}' file
00:50:56:a6:4c:35 eth0
However if you don't want to hardcode field positions then better alternative is this awk that processes each row and populates an array with name-value pairs:
awk -F ',[ \t]*|=+' '{for (i=1; i<NF; i+=2) {
gsub(/^"|"$/, "", $(i+1));
pair[$i] = $(i+1)}; print pair["ATTR{address}"], pair["NAME"]}' file
00:50:56:a6:4c:35 eth0
Upvotes: 1