sed处理OFX,从<memo>中提取收款人并在<name>上打印

时间:2016-07-07 19:19:55

标签: awk sed ofx

我正在处理OFX(银行交易)文件。我的银行未使用<NAME>标记来指定收款人,但此信息是<MEMO>代码的子字符串。

所以,我的文件是这样的:

...ofx headers and other stuff
...line below is a transaction
<STMTTRN>
    <TRNTYPE>OTHER</TRNTYPE>
    <DTPOSTED>20160609120000</DTPOSTED>
    <TRNAMT>-4.00</TRNAMT>
    <FITID>2016060914000</FITID>
    <CHECKNUM>000000700132</CHECKNUM>
    <REFNUM>700.132</REFNUM>
    <MEMO>Credit Card Payment - 09/06 18:37 Walmart 2th street</MEMO>
</STMTTRN>
...continues other transactions and end of file

我想匹配每个<MEMO>代码,提取收款人姓名(在此示例中为Walmart 2th street)并使用<NAME>写一个新行。我的输出就像:

...ofx headers and other stuff
...line below is a transaction
<STMTTRN>
    <TRNTYPE>OTHER</TRNTYPE>
    <DTPOSTED>20160609120000</DTPOSTED>
    <TRNAMT>-4.00</TRNAMT>
    <FITID>2016060914000</FITID>
    <CHECKNUM>000000700132</CHECKNUM>
    <REFNUM>700.132</REFNUM>
    <MEMO>Credit Card Payment - 09/06 18:37 Walmart 2th street</MEMO>
    <NAME>Walmart 2th street</NAME>
</STMTTRN>
...continues other transactions and end of file

awk的另一个工具可以是一个解决方案。

2 个答案:

答案 0 :(得分:2)

使用GNU sed:

sed -r 's/.*<MEMO>.* [0-9]{2}:[0-9]{2} (.*)<.*/&\n    <NAME>\1<\/NAME>/' file

输出:

<STMTTRN>
    <TRNTYPE>OTHER</TRNTYPE>
    <DTPOSTED>20160609120000</DTPOSTED>
    <TRNAMT>-4.00</TRNAMT>
    <FITID>2016060914000</FITID>
    <CHECKNUM>000000700132</CHECKNUM>
    <REFNUM>700.132</REFNUM>
    <MEMO>Credit Card Payment - 09/06 18:37 Walmart 2th street</MEMO>
    <NAME>Walmart 2th street</NAME>
</STMTTRN>

如果您要“就地”修改文件,请使用sed的选项-i

答案 1 :(得分:0)

补充@Cyrus回答处理no ascii chars:

我放弃了非ascii字符,现在它正在工作:

iconv -f "windows-1252" -t "UTF-8" file-ansi.ofx -o file-utf8.ofx
rm file-ansi.ofx
sed 'y/áÁàÀãÃâÂéÉêÊíÍóÓõÕôÔúÚüÜçÇ/aAaAaAaAeEeEiIoOoOoOuUuUcC/' -i file-utf8.ofx
sed -i -r 's/.*<MEMO>.* [0-9]{2}:[0-9]{2} (.*)<.*/&\n                  <NAME>\1<\/NAME>/' file-utf8.ofx 

我的输出:

<MEMO>Cartao de Credito - 09/06 18:37 Walmart 2th</MEMO>
<NAME>Walmart 2th street</NAME>