Removal of unnecessary white spaces

Thursday, June 20, 2013 , 1 Comments

I have a text file which looks something like this:
1, 2, 3, "Test, Hello"
4, 5, 6, "Well, Hi There!"
You can see that there is a space after comma(,) which i feel its not needed for me. But I need that space in between the string in last field. So the output I am expecting is :
1,2,3,"Test, Hello"
4,5,6,"Well, Hi There!"
I used the below command for doing the same:
perl -lne 'if(/(.*?\")(.*)/)
           print "$a$b"}' your_file
capture thye string till " in $1 and and remaining in $2.
$2 should be obviously unchanged. so store it in $b
$1 should be changed . so store it in $a and replace all ", " with ",".

Same thing can be achieved in awk as below:
nawk -F'\"' -v OFS='\"' '{gsub(/ /,"",$1)}1' your_file

1 comment:

  1. You could also do this with Perl's Text::CSV module.

    Interestingly, if we allow_whitespace, then there's nothing else to do; we just read it in and write it back out!

    $ ./ < temp
    1,2,3,"Test, Hello"
    4,5,6,"Well, Hi There!"