更智能地删除不必要的空白 CSV [英] Smarter Removing Unnecessary WhiteSpace CSV

查看:25
本文介绍了更智能地删除不必要的空白 CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于以下内容的逗号分隔文件 (CSV)

I have a comma separated file (CSV) that resembles the following

1, 2, 3, "Test, Hello"
4, 5, 6, "Well, Hi There!"

我需要能够将上述内容从 Linux 命令行理想地转换为

I need to be able to transform the above from a Linux command line ideally into

1,2,3,"Test, Hello"
4,5,6,"Well, Hi There!"

现在,我知道其他一些解决方案,例如:删除所有逗号后的空格

Now, I am aware of some of the other solutions like: Removing spaces after all commas

然而,这并不知道用双引号括起来的字符串.比如页面上的解决方案:

This, however was not aware of strings which were enclosed in double quotes. For example, the solution on the page:

sed -e 's/s+,/,/g'

产生...

1,2,3,"Test,Hello"
4,5,6,"Well,Hi There!"

不一样!此方法删除了封闭字符串中的空格.有没有人知道如何在不破坏双引号中的空格的情况下删除空格?或者如果这太难了,改为特定的领域?

IT IS NOT THE SAME! This method removed the spaces within the enclosed string. Does anybody have an idea how to remove white spaces without destroying that which is enclosed in double quotes? Or if that is too difficult, a specific field instead?

推荐答案

perl -lne 'if(/(.*?")(.*)/){$b=$2;$a=$1;$a=~s/,[s]/,/g;print "$a$b"}' your_file

测试如下:

> cat temp
1, 2, 3, "Test, Hello"
4, 5, 6, "Well, Hi There!"
>
> perl -lne 'if(/(.*?")(.*)/){$b=$2;$a=$1;$a=~s/,[s]/,/g;print "$a$b"}' temp
1,2,3,"Test, Hello"
4,5,6,"Well, Hi There!"
> 

或者你可以使用 awk(我使用了 nawk,因为我在使用 solaris):

Or you can use awk (i used nawk since i am working on solaris):

nawk -F'"' -v OFS='"' '{gsub(/ /,"",$1)}1' your_file

这篇关于更智能地删除不必要的空白 CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆