替换引号中间的空格

10

我有一行来自日志文件:

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

我想替换引号中间的空格,这样我就可以使用空格作为分隔符提取列。结果可能是这样的:

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

我自己没有找到适用于sed的正则表达式。非常感谢你的帮助。Martin

5个回答

8
将您的日志文件通过此awk命令传输:
awk -F\" '{OFS="\"";for(i=2;i<NF;i+=2)gsub(/ /,"@",$i);print}'

3

感谢您提供的所有答案。

这是我最终使用的Perl单行代码:

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

IT技术相关内容需要提供

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

.


这需要在引号之间至少有一个字符。如果您还想支持零个字符,请使用星号 * 字符:perl -pe 's{("[^\"]*")}{($x=$1)=~s/ /@/g;$x}ge' - EdwardTeach

2

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"

1

通过使用双引号作为RS,所有偶数记录都是在双引号内的记录。替换这些偶数记录中的空格。由于输出记录分隔符默认为换行符,因此将其更改为双引号。

awk 'BEGIN {RS="\"";ORS="\"" }{if (NR%2==0){gsub(/ /,"@",$0);print $0}else {p
rint $0}}' InputText.txt

1
这会在新行上留下一个尾随的 " - Orwellophile

0
如果你决定用更具有功能的perl替换sed,那么这里有一个一行代码可以满足你的需求:
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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接