Search code examples
stringbashunixsearchcut

How to search through a string and extract the required value in unix


I have a string like below

QUERY_RESULT='88371087|COB-A#2014-04-22,COB-C#2014-04-22,2014-04-22,2014-04-23 88354188|COB-W#2014-04-22,2014-04-22,2014-04-22 88319898|COB-X#2014-04-22,COB-K#2014-04-22,2014-04-22,2014-04-22'

This is a result taken by querying the database. Now I want to take all the values before the pipe and separate it with coma. So the output needed is :

A='88371087,88354188,88319898'

The db values can be different every time, there can be just one value or 2 or more values How do I do it.


Solution

  • Using awk

    A=`echo $QUERY_RESULT | awk '{ nreg=split($0,reg);for(i=1;i<=nreg;i++){split(reg[i],fld,"|");printf("%s%s",(i==1?"":","),fld[1]);}}'`
    
    echo $A
    
    88371087,88354188,88319898