user2656114
user2656114

Reputation: 980

Remove spaces between commas using command line

If I have a file like

1050505,Some Customer,  1  ,  1  ,Some Order, 5  ,  6  Item
1050505,Some Customer,  1  ,  1  ,Some Order, 5  ,  6  Item
1050505,Some Customer,  1  ,  1  ,Some Order, 5  ,  6  Item
1050505,Some Customer,  1  ,  1  ,Some Order, 5  ,  6  Item
1050505,Some Customer,  1  ,  1  ,Some Order, 5  ,  6  Item

But I need to strip spaces except for when they are between words (i.e. strip spaces after or before a comma).

1050505,Some Customer,1,1,Some Order,5,6  Item

What would be the simplest method of doing this by standard command line?

Upvotes: 2

Views: 2150

Answers (3)

Kyle Burton
Kyle Burton

Reputation: 27588

You can do this with a couple of tools. Perl:

perl -pe 's/\s*,\s*/,/g;' file.txt

sed:

sed 's/,\s\+/,/g; s/\s\+,/,/g' < file.txt

awk:

awk '{gsub(", +", ",", $0); gsub(" +,", ",", $0); print $0}' file.txt

Upvotes: 3

Vijay
Vijay

Reputation: 67319

perl -pi -e 's/[\s]+,/,/g;s/,[\s]+/,/g' your_file

Upvotes: 0

Petter
Petter

Reputation: 4165

A simple sed command would do it:

sed -i 's/,[ ]*/,/g' /path/to/file

Upvotes: 0

Related Questions