0

I would like to write a shell script. It will take in a .txt file and output a .csv file.

The .txt file is a two dimensional array of text. But there is an unknown number of spaces between each entry.

So for example, the inputted file might look like:

Name    Subject   Grade
Fred English      A
James   French  B
Mark      Maths      D

And I want it to look like

Name,Subject,Grade
Fred,English,A
James,French,B
Mark,Maths,D

In pseudocode it would be:

  1. search for the string containing two spaces and replace with a single space

  2. repeat 1. until no more changes are being made (or just 10 times, say)

  3. replace " " with ","

Any ideas?

3 Answers 3

2

You can do it in one step:

sed 's/  */,/g'
Sign up to request clarification or add additional context in comments.

2 Comments

Why not ` +` instead of ` *`?
@MrTux It just doesn't work: + is part of so called "extended" regular expression. Would require to write sed -r 's/ +/,/' to work.
0

It's not shell, but a perl one-liner:

perl -pi -e 's| +|,|g' filename.txt

Comments

0
tr -s ' ' , < input-file.txt

Comments

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.