Sunday, October 24, 2021

[SOLVED] How to grep a column?

Issue

Sorry guys, i would like to know, if it possible to grep column? For example, we have output like (vmstat):

procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
 0  0      0 706108  75536 328172    0    0   142    88  489 1042  5 11 84  0

If I run ./script.sh in output will be:

$ ./script.sh in
$ 489

Or maybe not grep, but i need use only bash (preparing for the exam). Thanks in advance.


Solution

I guess what you wanted was, you gave a column title as argument, like in, buff or wa... and you get the corresponding value.

so try this:

vmstat|awk -v f="in" '!o{for(x=1;x<=NF;x++)if($x==f){o=1;next}}o{print $x}'

here the f="in" is the column header. "in" was hardcoded, it could be shell variable like f="$foo"

small test, I saved your vmstat output as out file:

kent$  cat out
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
 0  0      0 706108  75536 328172    0    0   142    88  489 1042  5 11 84  0

kent$  awk -v f="in" '!o{for(x=1;x<=NF;x++)if($x==f){o=1;next}}o{print $x}' out
489

kent$  awk -v f="buff" '!o{for(x=1;x<=NF;x++)if($x==f){o=1;next}}o{print $x}' out         
75536


Answered By - Kent