Wow, I finally made it! It took me few days of night and coffee to come up this solution. This vi / vim Regular Expression can replace / substitute the commas inside quotes (substitute inside substitute). CSV Comma separated values
Sample Text:
"Hello,World", "vi, vim, gvim, is a really fun editor"
"I am really, really, really, excited", "it,made,my,day."
Replace Commas Inside Quotes:
%s/"\([^"]\+\)"/\=substitute(submatch(0), ',', '_', 'g')/g
Sample Output:
"Hello_World", "vi_ vim_ gvim_ is a really fun editor"
"I am really_ really_ really_ excited", "it_made_my_day."
Run it in batch script:
@echo off
vim -S replace5.vim test.txt
:: http://gala4th.blogspot.com/2008/12/vi-vim-remove-replace-comma-commas.html
echo Done!
PAUSE
replace5.vim:
:set nobackup
:argdo! %s/"\([^"]\+\)"/\=substitute(submatch(0), ',', '_', 'g')/g update
:wq
Final Version:
@echo off
:: replace7.vim does three things:
:: 1) remove the first line.
:: 2) replace all commas inside quotes to underscore (_)
:: 3) Remove all quotes
vim -S replace7.vim test.txt
:: http://gala4th.blogspot.com/2008/12/vi-vim-remove-replace-comma-commas.html
echo Done!
PAUSE
replace7.vim
:set nobackup
:argdo! 1,1s/^.\+\n//
:argdo! %s/"\([^"]\+\)"/\=substitute(submatch(0), ',', '_', 'g')/g
:argdo! %s/"//g | update
:wq
Perl Version:
#!C:\Perl\bin\perl.exe
$str = '123, "how, are, you", "i, am", "fine, thank, you, and, you"';
$str=~ s/("[^"]+")/remove($1,$1)/eg;
print $str;
sub remove {
my( $self, $s ) = @_;
# find: quote, comma, smart quote (left), smart quote (right)
# replace: nothing
# note: can use {$1} to separate other text
$s =~ s/"|,|\x93|\x94//g;
return $s;
}
See Also: http://gala4th.blogspot.com/2008/12/vi-vim-gvim-find-search-replace-string.html
Reference:
http://www.nminus.org/vim/
http://www.geocities.com/volontir/
http://www.guckes.net/vi/substitute.html
http://vimdoc.sourceforge.net/htmldoc/change.html
http://www.vim.org/htmldoc/pattern.html
http://vim.wikia.com/wiki/Using_an_expression_in_substitute_command
http://www.jason.mock.ws/wordpress/2005/10/28/vim-tips
No comments:
Post a Comment