Skip to content
Advertisement

Storing only part of output into shell variable

hi i am using a bash script. here i execute this code.

/usr/bin/mxci <<EOF
SELECT substring(substring(tname from (1+locate('.',tname))),
(1+locate('.',substring(tname from (1+locate('.',tname))))),15 ) as TAB_NAME
FROM table(explain('/home/vivek/MFCABS1031VCAT.VSCH.A9B69395AE3238A4184A90CD1F28C161', '%'))
WHERE OPERATOR LIKE '%FILE_SCAN%';
EOF'

This will return a output as

>>SELECT substring(substring(tname from (1+locate('.',tname))),
+>(1+locate('.',substring(tname from (1+locate('.',tname))))),15 ) as TAB_NAME
+>FROM table(explain('/home/vivek/MFCABS1031VCAT.VSCH.A9B69395AE3238A4184A90CD1F28C161', '%'))
+>WHERE OPERATOR LIKE '%FILE_SCAN%';

TAB_NAME
---------------

TEST1

--- 1 row(s) selected.
>>exit;

Now i know how to store this entire output into a single variable and print it But i am not able to figure out how to store partial information into variable. Like if i want to store only TEST1 into the variable, what should i do.

Thanks in advance

The output of the varaible Test

/home/vivek: echo "$test"
Hewlett Packard Enterprise NonStop(TM) SQL/MX Conversational Interface 3.7
(c) Copyright 2003-2019 Hewlett Packard Enterprise Development LP.
>>SELECT substring(substring(tname from (1+locate('.',tname))),
+>(1+locate('.',substring(tname from (1+locate('.',tname))))),15 ) as TAB_NAME
+>FROM table(explain('/home/vivek/MFCABS1031VCAT.VSCH.A9B69395AE3238A4184A90CD1F28C161', '%'))
+>WHERE OPERATOR LIKE '%FILE_SCAN%';

TAB_NAME
---------------

TEST1

--- 1 row(s) selected.
>>exit;

End of MXCI Session
/home/vivek:

Advertisement

Answer

You can pipe your output to this awk:

your_cmd | awk '/^TAB_NAME$/{n=NR} n && NR==n+3{print; exit}'

TEST1

This awk looks for a line that is equal to TAB_NAMES and stores that line no. Following which it prints a line whose line no is stored no + 3.

To store this shown value in a variable use:

myvar=$(your_cmd | awk '/^TAB_NAME$/{n=NR} n && NR==n+3{print; exit}')
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement