2012-11-26 26 views
1

我有看起来像这样的用sed来天真的文本文件转换成XML

BOOK|100004 
TRAN|A 
ANAM|Alberta 
TNAM|The School Act; the School Assessment Act. The Tax Recovery Act. The School Grants   Act. The School Attendance Act and General Regulations of the Department of Education 
PBLS|King's Printer 
SUB1|Alberta, Canada, Canadian Prairies, NOISBN 

我需要创建一个具有这种格式的XML文件中的记录文本文件,

<BOOK>100004</BOOK> 
<TRAN>A</TRAN> 
<first 4 chars> text data </ first 4 chars again> 

我认为我几乎没有像这样一个sed命令,

$sed 's#([:alpha:]\{4\})\|(*)#\<\1\>\2<\/\1\>#g' 

除非我得到这个错误: - sed: -e expression #1, char 41: invalid reference \1 on S'命令的[R HS'

任何sed专家都想将我推向启发路径?

回答

2

Sed使用旧式正则表达式,而不是'扩展'正则表达式,所以特殊字符的默认含义基本相反:'plain'sed中的捕获组是\(...\),而不是(...)。与逃脱的|字符一样:转义它变成交替。一个工作sed脚本的样子:

sed 's#\([^|]\+\)|\(.*\)#<\1>\2</\1>#' 

如果你想使用正则表达式的扩展,可以使用-r标志:

sed -r 's#([^|]+)\|(.*)#<\1>\2</\1>#' 
+0

太感谢你了! –