Linux: convert column to row when needed

April 4, 2016

I was configuring a Linux server and it required me to install the same list of PHP 7 packages that were installed on a different server running Ubuntu. Installed packages on Debian based Linux distributions may be obtained using the dpkg command, as follows:

dpkg -l

The above generates a list with several columns, while the second column contains the package name that we need. Limiting the list to PHP 7 packages only is done by piping the output to the grep command, straight-forward, no biggies. To get rid of the unnecessary columns, we call in awk to print only the required column. Yes, that prints a neat column. However if we would like the list in one row, separated by a space, to be used in another apt-get operation, we could trim the “new lines” and replace by a space… simply said, we call the tr command.

Summing up in one line, we have…

dpkg -l | grep php7 | awk ‘{ print $2 }’ | tr ‘\n’ ‘ ‘