replace spaces only in between quotation marks

2020-07-06 07:40发布

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

标签: sed awk
5条回答
倾城 Initia
2楼-- · 2020-07-06 07:52

Pipe your log file through this awk command:

awk -F\" '{OFS="\"";for(i=2;i<NF;i+=2)gsub(/ /,"@",$i);print}'
查看更多
狗以群分
3楼-- · 2020-07-06 07:53

If you decide to swap sed with more feature rich perl then here is one liner to get what you need:

line='field 1234 "text in quotes" 1234 "other text in quotes"'
echo $line | perl -pe 's#("[^"]*")#sub{$p=$1; $p =~ tr/ /@/; return $p}->()#eg'

Output: field 1234 "text@in@quotes" 1234 "other@text@in@quotes"
查看更多
女痞
4楼-- · 2020-07-06 08:07

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"

.

查看更多
beautiful°
5楼-- · 2020-07-06 08:17

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
查看更多
看我几分像从前
6楼-- · 2020-07-06 08:19

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"
查看更多
登录 后发表回答