Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace spaces only in between quotation marks

Tags:

sed

awk

I have line from log file:

field 1234 "text in quotes" 1234 "other text in quotes"

I would like to replace spaces in between quotes, so I could than extract columns using space as delimiter. So the result could be something like

field 1234 "text@in@quotes" 1234 "other@text@in@quotes"

I was not able to find out working regex for sed myself. Thanks a lot for help. Martin

like image 397
Martin Avatar asked Mar 31 '11 12:03

Martin


4 Answers

Pipe your log file through this awk command:

awk -F\" '{OFS="\"";for(i=2;i<NF;i+=2)gsub(/ /,"@",$i);print}'
like image 93
Mackie Messer Avatar answered Oct 11 '22 12:10

Mackie Messer


Thanks for all answers.

This is perl one-liner I finally use:

perl -pe 's{("[^\"]+")}{($x=$1)=~s/ /@/g;$x}ge'

it results in required

field 1234 "text@in@quotes" 1234 "other@text@in@quotes"

.

like image 30
Martin Avatar answered Oct 11 '22 13:10

Martin


Ruby(1.9+)

$ cat file
field 1234 "text in quotes" 1234 "other text in quotes"

$ ruby -ne 'print $_.gsub(/(\".*?\")/){|x| x.gsub!(/\s+/,"@") }'  file
field 1234 "text@in@quotes" 1234 "other@text@in@quotes"
like image 2
kurumi Avatar answered Oct 11 '22 13:10

kurumi


by using double quote as RS all even records are the ones inside double quotes. replace space in those even records. Since output records separator is newline by default ,change it to double quote.

awk 'BEGIN {RS="\"";ORS="\"" }{if (NR%2==0){gsub(/ /,"@",$0);print $0}else {p
rint $0}}' InputText.txt
like image 1
siddardha Avatar answered Oct 11 '22 12:10

siddardha