• Uncategorized

About linux : Ubuntu-terminal-data-into-a-csv-file

Question Detail

I am trying to save the data result I got from the terminal as a .csv file.

The data is something like this:

1     558
2     576
3     492
500   517

Is there any command line I can run so that a .csv file can be created from the data I have?

Question Answer

There is no simple facility for scrolling back and selecting parts of the output you already received (though of course, if you like, you can select something with the mouse and copy/paste into an editor and save it from there), but if you can run the same command again and get the same results, run it again and redirect to a file, perhaps with simple postprocessing.

some-command -with arguments -and -options >output.txt

The result you shows looks like tab-separated data, which is already basically CSV, only with tabs instead of comma (TSV). If there are no other commas in the data, tr '\t' ',' will change all the tabs into commas, yielding a CSV file.

some-command -with arguments -and -options | tr '\t' ',' >output.csv

In more complex cases, you may need to use various standard Unix utilities to perform more elaborate postprocessing tasks. Make sure you are familiar with the basic tools (tr, cut, paste, etc) as well as at least the basics of the standard scripting languages sed and Awk.

Ultimately, you might want to familiarize yourself with a modern scripting language like Python, which has a well-documented csv module as part of its standard library, and a fairly relaxed learning curve.

If the “data” is inside a file and we assume it contains spaces like your message includes;


Without using cat:

tr -s " " < <data_file> | sed -n 's/ /,/p' > <any_file_name>.csv

If your data is an output you can:

<output> | tr -s " " | sed -n 's/ /,/p' > <any_file_name>.csv

Before edit:

cat <data_file> | tr -s " " | sed -n 's/ /,/p' > <any_file_name>.csv

If you want any other csv file separator just change “,” with expected one like “\t” or “;” etc.

If your data is just an output you can pipeline it with replacing the cat <data_file> and go on like | tr -s " " | ... or write it to a file to cat like above.

You may also like...

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.