去除行内的所有空格,但不包括双引号内的空格

6

示例:

输入 =

This is an example text with    some      spaces. 
This should be 2nd line.
However the spaces between "quotes    should not    change".
last line.

输出 =

Thisisanexampletextwithsomespaces. 
Thisshouldbe2ndline.
Howeverthespacesbetween"quotes    should not    change".
lastline.
3个回答

5
awk '
    BEGIN {FS = OFS = "\""}
    /^[[:blank:]]*$/ {next}
    {for (i=1; i<=NF; i+=2) gsub(/[[:space:]]/,"",$i)} 
    1
' 

Thisisanexampletextwithsomespaces.
Thisshouldbe2ndline.
Howeverthespacesbetween"quotes    should not    change".
lastline.

3

使用GNU 进行示例:

$sed -r 's/(\".*\")|\s*/\1/g' file
这是一个带有一些空格的示例文本。
这应该是第二行。
但是“引号之间的空格不应更改”。
最后一行。

2

可以使用Perl来完成:

perl -pe 's{^\s*\n$}{}; s/ +(?=(([^"]+"){2})*[^"]*$)//g' file

这将删除所有空行或仅包含0个或多个空格的行,并在不在双引号之间时修剪空格。

在线演示:http://ideone.com/xizPNI


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接