[CentOS] Need help in writing a shell/bash script

Edo ml2edwin at gmail.com
Fri Dec 30 14:15:10 UTC 2011


Hi,


On Friday, December 30, 2011 at 9:00 PM, ankush grover wrote:

> Hi Friends,
>  
> I am trying to write a shell script which can merge the 2 columns into
> 3rd one on Centos 5. The file is very long around 31200 rows having
> around 1370 unique groups and around 12000 unique user-names.
> The 1st column is the groupname and then 2nd column is the user-name.


I’m not sure I understood that “2 columns into 3rd one” there but...
  
> 1st Column (Groupname) 2nd Column (username)
> admin ankush
> admin amit
> powerusers dinesh
> powerusers jitendra


If that’s the format of your input and …

> The desired output should be like this
>  
> admin: ankush, amit
> powerusers: dinesh, jitendra
>  

If that’s your desired output, and assuming the input file is already sorted, try the ff:

# -- code starts here -->
#!/bin/bash

GROUPNAMENOW=''

while read LINE
do
  GROUPNAME=$(echo $LINE | cut -d ' ' -f 1)
  USERNAME=$(echo $LINE | cut -d ' ' -f 2)
  if [ "$GROUPNAME" == "$GROUPNAMENOW" ]; then
    echo ", $USERNAME"
  else
    GROUPNAMENOW=$GROUPNAME
    echo -n "$GROUPNAMENOW: $USERNAME"
  fi
done < input.txt



# <-- code ends here --

Note: Tested and worked as expected in OS X. It should work in CentOS too.

HTH,

--  
- Edo - mailto:ml2edwin at gmail.com
“Happy are those conscious of their spiritual need …”
—Matthew 5:3







More information about the CentOS mailing list