Skip to content
Home ยป How to Convert a Column into a Row in a Linux File?

How to Convert a Column into a Row in a Linux File?

I want to convert a file containing a column into a row in a Linux file.

 

Problem

How to convert a column into a row in a Linux file?

 

Solution

For your information, columns are vertical, or what you arrange from top to bottom, while rows are horizontal, or what you can arrange from left to right. Consider the picture below to distinguish between columns and rows:

Columns vs rows

 

For example, you have a test.txt file as shown below:

The test.txt file

 

To convert into a row, use the command below:

awk 'BEGIN { ORS=" " } { print } END { print "\n" }' test.txt

 

Then the file changes to as shown below:

Using the awk command

 

You can also use the command below:

tr '\n' ' ' < test.txt && echo

 

So that the file becomes as shown below:

Using the tr command

 

Or you can also use the command below:

paste -sd" " test.txt

 

To make the file look like this:

convert a column into a row
Using the paste command

 

Note

If you want to enter the results in a file, for example, the result.txt file, then you can use the standard output redirection or stdout on Linux. For example, you use the awk command to change the file, so you can use the command below:

awk 'BEGIN { ORS=" " } { print } END { print "\n" }' test.txt > result.txt

 

Then the results of these changes are in the result.txt file as shown below:

convert a column into a row
Using the redirection to save the result

 

Likewise, by using the two commands above, you can simply add stdout at the end of the two commands.

 

References

keydifferences.com
community.unix.com

image_pdfimage_print
Visited 43 times, 1 visit(s) today
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *