LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Formatting rows and columns (https://www.linuxquestions.org/questions/programming-9/formatting-rows-and-columns-829458/)

kdelover 08-31-2010 02:13 AM

Formatting rows and columns
 
Hi,i have a simple table some thing like this.

100 user1
101 user1
210 user3
122 user4
120 user3
111 user2
099 user2

How do i format this,such that the data presented is in this form.

user1 100 101
user3 210 120
user2 111 099
user4 122

how do i get this formatting using gawk or sed. Thanks

grail 08-31-2010 02:27 AM

Have you tried anything? Where are you stuck? I would suggest using (g)awk as it would be trivial.

druuna 08-31-2010 02:32 AM

Hi,

Something like this:
Code:

#!/bin/bash

sort -k2 infile | \
awk '{ userArray[$2] = userArray[$2]" "$1 }
END { for ( item in userArray )
    print item, userArray[item] }'

Example run:
Code:

$ cat infile
100 user1
101 user1
210 user3
122 user4
120 user3
111 user2
099 user2

$ ./awk.format.rows.columns.sh
user1  100 101
user2  099 111
user3  120 210
user4  122

Hope this helps.

EDIT: Did not see grail's reply. He does have a good point, do post what you have tried and what doesn't (seem to) work.

ghostdog74 08-31-2010 02:39 AM

Code:

#!/bin/bash
#bash 4.0
declare -A array
exec 4<"file"
while read -r a b
do
  array[$b]+="$a "
done <&4
exec 4<&-

for i in ${!array[@]}
do
  echo $i ${array[$i]}
done


gnashley 08-31-2010 02:56 AM

You might try the 'fmt' command also.


All times are GMT -5. The time now is 04:16 AM.