Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: bash script to join similar lines together  (Read 6245 times)

0 Members and 1 Guest are viewing this topic.

rei125

    Topic Starter


    Newbie

    • Experience: Beginner
    • OS: Unknown
    bash script to join similar lines together
    « on: June 27, 2012, 07:46:51 PM »
    Hi,

    I have been thinking of how to script this but i have no clue at all..
    Could someone please help me out or give me some idea on this?

    I would like to group those lines with the same first variable in each line, joining the 2nd variables with commas.
    Let's say i have the following input.
    Code: [Select]
    aa c1
    aa c2
    aa c3
    cc d1
    dd e1
    dd e2
    ee f1

    I would like the output to be like this.
    Code: [Select]
    aa c1,c2,c3
    cc d1
    dd e1,e2
    ee f1

    Could this be easily done with bash script?
    Or should i try perl script then?
    I'm a beginner in bash script and perl.

    Thank you.

    rei125

      Topic Starter


      Newbie

      • Experience: Beginner
      • OS: Unknown
      Re: bash script to join similar lines together
      « Reply #1 on: June 29, 2012, 01:44:40 AM »
      I've found a way to solve this.
      ${input} is the filename for the input file.

      Code: [Select]
      for m in `cat ${input} | awk '{print $1}' | sort | uniq `
      do
              var=`grep "^${m} " ${output} | awk '{print $2}' | tr '\n' ',' | sed '$s/,$//'`
              echo "${m} ${var}"
      done