Maverick
Maverick

Reputation: 145

How can I pipe a command output to a CSV file in shell?

~]$ date;daemon -ip statistics data | grep bytes

Fri Jun 22 13:58:37 +08 2018
1958391001 transmit bytes
1825330799 receive bytes

I want to Pipe these value to a CSV file as mentioned below.How can I do it?

|Date| Tx bytes|Rx Bytes|

Upvotes: 0

Views: 1142

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207678

Like this with awk:

daemon -ip statistics data | awk -v d="$(date)" '/transmit bytes/{t=$1} /receive bytes/{print "|" d "|" t "|" $1 "|"}' 

Output

|Fri 22 Jun 2018 08:29:45 BST|1958391001|1825330799|

Or, if you prefer printf-style formatting:

daemon -ip statistics data | awk -v d="$(date)" '/transmit bytes/{t=$1} /receive bytes/{printf("|%s|%d|%d|\n",d,t,$1)}'

Upvotes: 1

user1934428
user1934428

Reputation: 22291

If you pipe the output of your command to tr in order to replace newlines by your separator, i.e.

....|tr '\n' '|'

you nearly have your whole string already complete, except for the leading |. So, if you store this string to a variable, i.e.

v=$(.....|tr '\n' '|')

you can append it to your csv file with

echo "|$v" >>your_file.csv

Upvotes: 0

Related Questions