CharlesD
CharlesD

Reputation: 111

Bash - Read in a file and replace multiple spaces with just one comma

I'm trying to write a bash script that will take in a file with spaces and output the same file, but comma delimited. I figured out how to replaces spaces with commas, but I've run into a problem: there are some rows that have a variable number of spaces. Some rows contain 2 or 3 spaces and some contain as many as 7 or 13. Here's what I have so far:

sed 's/ /,/g' $varfile > testdone.txt

$varfile is the file name that the user gives.

But I'm not sure how to fix the variable space problem. Any suggestions are welcome. Thank you.

Upvotes: 2

Views: 838

Answers (2)

William Pursell
William Pursell

Reputation: 212654

This is not a job for sed. tr is more appropriate:

$ printf 'foo      bar\n' | tr -s ' ' ,
foo,bar

The -s tells tr to squash multiple occurrences. Also, you can generalize with tr -s '[:space:]' , (which will replace newlines, perhaps undesirable) or tr -s ' \t' , to handle spaces or tabs.

Upvotes: 6

glenn jackman
glenn jackman

Reputation: 247210

You just need to use the + quantifier to match one or more

Assuming GNU sed

sed 's/ \+/,/g' file
# or
sed -E 's/ +/,/g' file

With GNU basic regular expressions, the "one or more" quantifier is \+
With GNU extended regular expressions, the "one or more" quantifier is +

Upvotes: 2

Related Questions