【问题标题】:Remove all spaces in lines but not between double quotes删除行中的所有空格,但不删除双引号之间的所有空格
【发布时间】:2013-06-22 13:30:11
【问题描述】:
示例:
输入 =
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.
【问题讨论】:
标签:
regex
perl
sed
awk
pattern-matching
【解决方案1】:
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.
【解决方案2】:
以 GNU sed 为例:
$sed -r 's/(\".*\")|\s*/\1/g' 文件
这是一个带有一些空格的示例文本。
这应该是第二行。
然而,“引号之间的空格不应改变”。
最后一行。
【解决方案3】:
可以使用 perl 完成:
perl -pe 's{^\s*\n$}{}; s/ +(?=(([^"]+"){2})*[^"]*$)//g' file
这将删除所有空白行或仅包含 0 个或多个空格的行,并在不在双引号之间时修剪空格。