Render a CSV across multiple columns on the terminal/shell
I was recently working with a CSV file that contained a bunch of words and I wanted to render them on the console so that you could see all of them at once without any scrolling. i.e. I wanted the rendering of the CSV file to wrap across columns.
I learned that we can do exactly this using the paste
command, so let’s see how to do it.
Imagine we have the CSV file shown below:
hello |
---|
goodbye |
house |
shell |
dog |
cat |
hat |
chat |
bottle |
phone |
To render this file to the terminal, we could do the following:
cat data/words.csv
That renders each word on its own line:
hello
goodbye
house
shell
dog
cat
hat
chat
bottle
phone
With the paste
command, we can concatenate corresponding lines in a file.
The paste
command usually takes a file name as argument, but we can tell it to use stdin
by using the -
parameter.
So, the following, would render the contents of the file line-by-line:
cat data/words.csv | paste -
But, if we pass in more -
, it will concatenate the lines together:
If ‘-’ is specified for one or more of the input files, the standard input is used; standard input is read one line at a time, circularly, for each instance of ‘-’.
So, if we want to create two columns of words, we’d do this:
cat data/words.csv | paste - -
hello goodbye
house shell
dog cat
hat chat
bottle phone
And if we want 5 columns, we’d instead pass -
5 times:
cat data/words.csv | paste - - - - -
hello goodbye house shell dog
cat hat chat bottle phone
Pretty neat!
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.