2

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.

1
  • awk -v OFS=, '{$1=$1}1' "$varfile" Commented Dec 11, 2018 at 21:05

2 Answers 2

6

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.

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

Comments

2

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 +

1 Comment

sed 's/ \{1,\}/,/g' should work with any POSIX-compliant version of sed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.