Linux Command for Exporting Output to a Csv File in Separated Columns

Linux Command for Exporting Output to a Csv File in Separated Columns

I am wondering when using Linux command line, how can I output a result i grep to a CSV file in different columns.

Here are the columns i grep from 'last' command

The final format, I would like to achieve, right now I have to import the data manually from a txt file is the following:

2

3 Answers

You only need to replace the tab with comas and set the output to a csv file:

grep "hello    world" | tr "\\t" "," > file.csv

the text in grep can be a cat to your file to get all the content

I'm not sure if it is a tab or only a white space on your output, in case there is a white space:

grep "hello world" | tr " " "," > file.csv
2

Another way is to sed the output with

df -h | sed -E 's/ +/,/g'

In my case I needed to grab the df output.

The Plus-sign is a multiplicator (one or more of in this case), and the substitution is ,. The -E must be used, because we want to use regex.

last | awk '{print $3,$4,$5,$6,$8,$9}' > gift.xls

This command is perfect for your requirements.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.