Kian
Kian

Reputation: 3229

Remove white space using a Unix shell script

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?

Upvotes: 0

Views: 1213

Answers (3)

William Pursell
William Pursell

Reputation: 212268

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

Upvotes: 0

MrTux
MrTux

Reputation: 34003

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

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

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96266

You can do it in one step:

sed 's/  */,/g'

Upvotes: 2

Related Questions