Reputation: 68
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.csv
file 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
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
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
Reputation: 133528
@Kart: Could you please try following.
awk '{$1=$1;} 1' OFS=, Input_file > output.csv
I hope this helps you.
Upvotes: 2