Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all spaces in lines but not between double quotes

Example:

input =

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

output =

Thisisanexampletextwithsomespaces. 
Thisshouldbe2ndline.
Howeverthespacesbetween"quotes    should not    change".
lastline.
like image 958
sudeepto roy Avatar asked Jun 25 '13 16:06

sudeepto roy


2 Answers

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.
like image 104
glenn jackman Avatar answered Sep 19 '22 10:09

glenn jackman


Example with GNU sed:

$sed -r 's/(\".*\")|\s*/\1/g' file
Thisisanexampletextwithsomespaces.
Thisshouldbe2ndline.
Howeverthespacesbetween"quotes    should not    change".
lastline.
like image 27
captcha Avatar answered Sep 22 '22 10:09

captcha