Search code examples
shellunixscriptingsolaris

I only want to display the matching users up until the comma


I want to print the color along wit the users who match, not all the users. So I want to find bob and riley and only print the data associated with them and not the other users. If there is no matches I would like the whole line just to be skipped and not display anything

How can I achieve this?


awk '{ FS=":"; print $1 " " $4 }' /test|while read color person
do
   if [[ `echo ${users}|egrep -i "bob|riley"` ]]
   then
   printf " ${color} - ${person}\n\n"
   fi
done

used FS because in the file there are 4 field separated by the ":"

Input looks something like this:

red: :car:todd,riley,bob,greg                 
green: :jeep:todd,riley,bob,greg,thomas                                                    
black: :truck:jamie,jack,bob,travis,riley

Output currently:

red - todd,riley,bob,greg
green - todd,riley,bob,greg,thomas
black - jamie,jack,bob,travis,riley

Desired output

red - bob,riley
green - bob,riley
black - bob,riley

Doesn't have to be sorted like this but it would be helpful


Solution

  • When you have GNU grep available, you can use option -o (--only-matching)

    echo ${person} | egrep -o -i -e "bob|riley"
    

    will show for the first line

    riley
    bob
    

    Now you can combine the results with tr

    echo ${person} | egrep -o -i -e "bob|riley" | tr '\n' ,
    

    gives

    riley,bob,
    

    And finally strip the trailing comma

    echo ${person} | egrep -o -i -e "bob|riley" | tr '\n' , | sed -e 's/,$//'
    

    which results in

    riley,bob