删除行中的所有空格,但不删除双引号之间的空格

时间:2013-06-25 16:25:59

标签: regex perl sed awk pattern-matching

实施例

输入=

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 个答案:

答案 0 :(得分:4)

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.

答案 1 :(得分:3)

GNU 的示例:

$sed -r 's/(\".*\")|\s*/\1/g' file
Thisisanexampletextwithsomespaces.
Thisshouldbe2ndline.
Howeverthespacesbetween"quotes    should not    change".
lastline.

答案 2 :(得分:2)

可以使用perl完成:

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

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

现场演示:http://ideone.com/xizPNI