0

(Couldn't come with any better title)

I'm trying to convert a number of lines, like these:

#define GENERIC_TYPE_METER_PULSE                     0x30 /*Pulse Meter*/
#define SPECIFIC_TYPE_NOT_USED                       0x00 /*Specific Device Class not used*/
......
#define MFG_ID_WAYNE_DALTON                          0x0008   //Wayne Dalton
#define MFG_ID_WILSHINE_HOLDING_CO_LTD               0x012D   //Wilshine Holding Co., Ltd
#define MFG_ID_WIDOM                                 0x0149   //wiDom
......
#define COMMAND_CLASS_ALARM                              0x71
#define COMMAND_CLASS_ALARM_V2                           0x71
#define COMMAND_CLASS_NOTIFICATION_V3                    0x71
#define COMMAND_CLASS_NOTIFICATION_V4                    0x71

in a file (c++) to something like these (for Java):

SPECIFIC_TYPE_NOT_USED((byte)0x00)             /*Specific Device Class not used*/
MFG_ID_WILSHINE_HOLDING_CO_LTD((byte)0x012D)   //Wilshine Holding Co., Ltd
COMMAND_CLASS_ALARM((byte)0x71)
....

I came up with this:

gawk '/^#define/ && / [[:xdigit:]]/ { printf "%s((byte)%s)\n",$2,$3 }'

but there are two issues - it doesn't work with awk; requires GNU-awk (gawk) and I also need the end-of-the-line comments in the output whenever available. How can I do that? I'm especially interested using awk but can live with sed as well. Cheers!!

4

3 に答える 3

2
$ cat tst.awk
/^#/ {
    hd[++nr] = sprintf("%s((byte)%s)", $2, $3)
    lgth = length(hd[nr])
    maxLgth = (lgth > maxLgth ? lgth : maxLgth)

    sub(/[^/]+/,"")
    tl[nr] = $0
}

END {
    for (i=1; i<=nr; i++)
        printf "%-*s%s\n", maxLgth+2, hd[i], tl[i]
}
$ awk -f tst.awk file
GENERIC_TYPE_METER_PULSE((byte)0x30)          /*Pulse Meter*/
SPECIFIC_TYPE_NOT_USED((byte)0x00)            /*Specific Device Class not used*/
MFG_ID_WAYNE_DALTON((byte)0x0008)             //Wayne Dalton
MFG_ID_WILSHINE_HOLDING_CO_LTD((byte)0x012D)  //Wilshine Holding Co., Ltd
MFG_ID_WIDOM((byte)0x0149)                    //wiDom
COMMAND_CLASS_ALARM((byte)0x71)
COMMAND_CLASS_ALARM_V2((byte)0x71)
COMMAND_CLASS_NOTIFICATION_V3((byte)0x71)
COMMAND_CLASS_NOTIFICATION_V4((byte)0x71)

2inmaxLgth+2を、最長値とそれに関連付けられたコメントの間の任意の間隔に変更します。

于 2013-10-25T19:41:58.613 に答える