awk find which column contains string

i want to search columns in a variable and any column contains a particular string, i want to print the value of that column

[skys ~]$ echo "${USEDMEMORY}"
memTotalReal=3925908 memAvailReal=1109812 memBuffer=242676 memCached=641628
[skys ~]$ 
[skys ~]$ echo "${USEDMEMORY}" | awk '/memAvailReal/'

so what im trying to do here is, find the column that contains the string "memAvailReal", then, output the value of "memAvailReal", so the desired output should be:

1109812

i dont want to hardcode a specific column number to grab because these strings may be in different columns.

Hello SkySmart,

Could you please try following and let me know if this helps.

echo "memTotalReal=3925908 memAvailReal=1109812 memBuffer=242676 memCached=641628" |  awk '{match($0,/memAvailReal=[0-9]+/);A=substr($0,RSTART,RLENGTH);sub(/.*=/,X,A);print A}'

Output will be as follows.

1109812

EDIT: Adding one more solution on same too.

echo "memTotalReal=3925908 memAvailReal=1109812 memBuffer=242676 memCached=641628" |  awk '{sub(/.*memAvailReal=/,X,$0);sub(/ .*/,X,$0);print}'

Thanks,
R. Singh

1 Like

thank you so much! this works perfectly

anyway to get rid of the echo? and have one command do it all? something like this:

awk -v USEDMEMORY="${USEDMEMORY}"  '{sub(/.*memAvailReal=/,X,$0);sub(/ .*/,X,$0);print}'

Hello SkySmart,

Could you please try following and let me know if this helps you(haven't tested though,but it should work).

VAL="memTotalReal=3925908 memAvailReal=1109812 memBuffer=242676 memCached=641628" 
awk -vval="$VAL"  'BEGIN{sub(/.*memAvailReal=/,X,val);sub(/ .*/,X,val);print val}'

Thanks,
R. Singh

1 Like

thank you! it works.

Non-AWK solution.

# in the middle
$ echo "memTotalReal=3925908 memAvailReal=1109812 memBuffer=242676 memCached=641628" | sed '/^.*memAvailReal=/ s///;s/ .*$//'
1109812
# at the start
$ echo "memAvailReal=1109822 memTotalReal=3925908 memBuffer=242676 memCached=641628" | sed '/^.*memAvailReal=/ s///;s/ .*$//'
1109822
# at the end
$ echo "memTotalReal=3925908 memBuffer=242676 memCached=641628 memAvailReal=1109842 " | sed '/^.*memAvailReal=/ s///;s/ .*$//'
1109842

As you can see it works wherever the required parameter is in the line. I am making the assumption that you would pipe the output of the process generating the line directly into the above sed command.

Andrew

1 Like

With a recent shell:

TMP=${USEDMEMORY#*memAvailReal=}
echo ${TMP%% *}
1109812
1 Like