How to add zeros between hex numbers with sed/awk?

[亡魂溺海] 提交于 2020-01-25 08:54:32

问题


I have file contains that strings

    abc = <0x12345678>;
    abc = <0x01234 0x56789>;
    abc = <0x123 0x456 0x789>;
    abc = <0x0 0x01234 0x0 0x56789>;
    abc = <0x012 0x345>, <0x678 0x901>;
    def = <0x12345 0x67890>;

I need to convert it to file contains

    abc = <0 0x12345678>;
    abc = <0 0x01234 0 0x56789>;
    abc = <0x123 0x456 0x789>;
    abc = <0x0 0x01234 0x0 0x56789>;
    abc = <0 0x012 0 0x345>, <0 0x678 0 0x901>;
    def = <0x12345 0x67890>;

So I need to add zeros before HEX numbers if strings starts with 'abc = ', that are no more than 2 HEX numbers between couple of triangular brackets and there isn't 0x0 between that HEX numbers. How I can do it with sed, awk or another bash tools?


回答1:


sed '/abc = </{/<[^ >]* [^ >]* /!s/0x/0 &/g}'

Explanation:

/abc = </{/<[^ >]* [^ >]* /!s/0x/0 &/g}
/abc = </                                Operate on lines containing "abc = <"
         {                            }  Group the commands together
                           !             Negate the condition
          /<[^ >]* [^ >]* /              Match if lines contain more than two elements after <
                            s/0x/0 &/    Prepend "0 " to "0x"
                                     g   Globally, i.e. replace as many times as possible


来源:https://stackoverflow.com/questions/58579677/how-to-add-zeros-between-hex-numbers-with-sed-awk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!