k189
k189

Reputation: 68

How to create a CSV file based on row in shell script?

I have a text file /tmp/some.txt with below values

JOHN              YES     6          6            2345762
 SHAUN             NO     6          6            2345748

I want to create a csv file with below format (i.e based on rows. NOT based on columns).

JOHN,YES,6,6,2345762
SHAUN,NO,6,6,2345748

i tried below code

for i in `wc -l /tmp/some.txt | awk '{print $1}'`
do
awk  'NR==$i' /tmp/some.txt | awk '{print $1","$2","$3","$4","$5}' >> /tmp/some.csv
done

here wc -l /tmp/some.txt | awk '{print $1}' will get the value as 2 (i.e 2 rows in text file). and for each row awk 'NR==$i' /tmp/some.txt | awk '{print $1","$2","$3","$4","$5}' will print the 5 fields into some.csvfile which is separated by comma.

when i execute each command separately it will work. but when i make it as a shell script i'm getting empty some.csv file.

Upvotes: 0

Views: 2359

Answers (4)

heemayl
heemayl

Reputation: 42017

With tr, squeezing (-s), and then transliterating space/tab ([:blank:]):

tr -s '[:blank:]' ',' <file.txt

With sed, substituting one or more space/tab with ,:

sed 's/[[:blank:]]\+/,/g' file.txt

With awk, replacing one ore more space/tab with , using gsub() function:

awk 'gsub("[[:blank:]]+", ",", $0)' file.txt

Example

% cat foo.txt
JOHN              YES     6          6            2345762
SHAUN             NO     6          6            2345748


% tr -s '[:blank:]' ',' <foo.txt                     
JOHN,YES,6,6,2345762
SHAUN,NO,6,6,2345748

% sed 's/[[:blank:]]\+/,/g' foo.txt                   
JOHN,YES,6,6,2345762
SHAUN,NO,6,6,2345748

% awk 'gsub("[[:blank:]]+", ",", $0)' foo.txt
JOHN,YES,6,6,2345762
SHAUN,NO,6,6,2345748

Upvotes: 1

Cyrus
Cyrus

Reputation: 88646

I suggest:

sed 's/[[:space:]]\+/,/g' /tmp/some.txt

Upvotes: 2

charli
charli

Reputation: 1778

You almost got it. awk already process the file row by row, so you don't need to iterate with the for loop.

So you just need to run:

awk '{print $1","$2","$3","$4","$5}' /tmp/some.txt >> /tmp/some.csv

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133528

@Kart: Could you please try following.

awk '{$1=$1;} 1' OFS=,   Input_file  > output.csv

I hope this helps you.

Upvotes: 2

Related Questions