user13166257
user13166257

Reputation:

Outputting text file to csv using bash

I am new to bash and I'm not sure how to do the following: I have a text file in the format:

123
John

234
Sally

456
Lucy

...

I want to output it to a csv file in the form:

123,John
234,Sally
456,Lucy
...

Upvotes: 0

Views: 56

Answers (1)

Quasímodo
Quasímodo

Reputation: 4004

A good job for sed:

sed '/[0-9]/{N;s/\n/,/}' txtfile

It detects lines having numbers and, when found, replaces the newline character by a comma.

If you also want to get rid of the blank lines in-between,

sed '/[0-9]/{N;s/\n/,/;n;d}' txtfile

Notice that if your file is as regular as the sample you gave, you don't even need the regex, 'N;s/\n/,/;n;d' would suffice.

Upvotes: 1

Related Questions