Convert coloumns to a row

May 4, 2010 at 21:11:19
Specs: RHEL5
Hi,
I have a requirement where i need to convert rows to a column. Below is the scenario explained.

Let’s assume that there was a file called users.lst. This file had the following data

web01 31
web02 32
web03 33
web04 34

i.e if you ran the command cat users.lst you would see the output similar to the above.

2) Now the idea is to write a script to convert the rows into one column. So let say the script was called format.sh. If you ran the script it should show the following output

31,32,33,34 web01|web02|web03|web04
We use the awk command for this.

Any answers would be gr8.

Thanks,
MS


See More: Convert coloumns to a row

Report •

#1
May 5, 2010 at 11:46:31
I do not want to do your homework, but I will get you started. You are going to have to read the file into 2 arrays with field 1 in one array and field 2 in the other, and then print the contents of the arrays with the proper commas and pipe symbols. You might even have to sort the arrays using GNU' awk's asort function.

Here is a code snipet that creates the arrays:

# UNTESTED
awk ' BEGIN { cnt=0;
   while ( getline < "users.txt" > 0 )
      {
      f1[cnt]=$1
      f2[cnt++]=$2
      }
}


Report •
Related Solutions


Ask Question