Linux: convert rows to columns with the paste command

Recently i had to deal with a script that produce row output

Linux: convert rows to columns with the paste command
Photo by Stefen Tan on Unsplash

Recently i had to deal with a script that produce row output$ script1.sh
server1 cpu 20%
server1 ram 10%
server1 disk 5%
server2 cpu 10%
server2 ram 20%
server2 disk 15%
server3 cpu 30%
server3 ram 40%
server3 disk 25%

But we want the output to be like thatserver1 cpu 20%,server1 ram 10%,server1 disk 5%
server2 cpu 10%,server2 ram 20%,server2 disk 15%
server3 cpu 30%,server3 ram 40%,server3 disk 25%

Bonus: Also we would like to eliminate the multiple occurrences of the server word and leave only one instanceserver1,cpu 20%,ram 10%,disk 5%
server2,cpu 10%,ram 20%,disk 15%
server3,cpu 30%,ram 40%,disk 25%

In order to convert the rows to columns we will use the paste command, the syntax we will use ispaste -d "," - - -

  • -d The delimiter to join rows
  • 3 dashes: combining three consecutive rows

Executing the following command will producescript.sh | paste -d "," - - -
server1 cpu 20%,server1 ram 10%,server1 disk 5%
server2 cpu 10%,server2 ram 20%,server2 disk 15%
server3 cpu 30%,server3 ram 40%,server4 disk 25%

The final step is to eliminate the multiple occurrences of the server word and leave only the first onescript.sh | paste -d "," - - - | sed 's/server.//2g' | sed 's/ /,/'server1,cpu 20%, ram 10%, disk 5%
server2,cpu 10%, ram 20%, disk 15%
server3,cpu 30%, ram 40%, disk 25%

I hope you found this short article useful :)