0

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.

1
  • 2
    why don't you just replace all blocks of spaces with a single comma? Commented Jan 9, 2017 at 14:07

4 Answers 4

2

@Kart: Could you please try following.

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

I hope this helps you.

Sign up to request clarification or add additional context in comments.

Comments

2

I suggest:

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

Comments

1

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

1 Comment

That's true, it's a better answer. I just used the same command @Kart wrote.
1

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

1 Comment

Nice! I wasn't aware that you can squeeze and replace in one shot with tr.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.