开发者

replace spaces only in between quotation marks

开发者 https://www.devze.com 2023-02-21 17:56 出处:网络
I have line f开发者_如何学编程rom log file: field 1234 \"text in quotes\" 1234 \"other text in quotes\"

I have line f开发者_如何学编程rom 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


Pipe your log file through this awk command:

awk -F\" '{OFS="\"";for(i=2;i<NF;i+=2)gsub(/ /,"@",$i);print}'


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"

.


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"


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


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"
0

精彩评论

暂无评论...
验证码 换一张
取 消