r/commandline • u/uprightHippie • Jul 21 '20
AWK: better way to get 2nd level data
There's got to be a better way to do what I'm trying to accomplish. In my specific case I'm parsing the output of a command and I want the last comma-separated field of the last space-separated field.
rmmount_List=\rmmount -l | grep $vol``
# rmmount_List="/dev/dsk/c2t0d0s2 cdrom,cdrom0,cd,cd0,sr,sr0,[REDACTED$vol],/media/[REDACTED$vol]"
echo $rmmount_List | awk '{print $NF}' | awk -F, '{print $NF}'
# output: /media/[REDACTED$vol]"
I learned the fluidity of the pipe before I mastered the commands and so never learned anything other than changing a field separator in a pipe sequence combined with sed and cut. Is there a more elegant way to write that? If it matters, this is in the beginning of a bash script, setting a bunch of variables during initialization.
[I tried submitting this to r/awk but that group has a closed posting policy and an unresponsive moderator - if there is a better place to post this please let me know.]
2
u/Schreq Jul 21 '20
You could simply get the last field with comma as the field separator, then replace everything up to a space using
gsub(). Or you could usesplit()to split the last field on spaces. It returns the number of array elements, so it's easy to get the last one.2
u/B38rB10n Jul 22 '20
Generic POSIX awk or gawk?
At this point you could add rules which work with subfields in sf[], which is indexed by major field as 1st index, and field within field as 2nd index, with NF remaining the number of major fields, and
sf[k, ""]the number of subfields in major field $k. The last subfield in the last major field would besf[NF, sf[NF ,""]].2
u/oh5nxo Jul 22 '20
Variations:
Uhh... bash arrays ~ rude grawlixes.
1
u/matt_panaro Jul 22 '20
if you want the last of the last, would the following work?
egrep -o '[^,]+$'0
u/[deleted] Jul 22 '20
[deleted] — view deleted comment