Home > Software design >  Ubuntu terminal data into a csv file
Ubuntu terminal data into a csv file

Time:12-30

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?

CodePudding user response:

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.

CodePudding user response:

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

Edit

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.

  • Related