Sed/awk/perl: modifica el texto conservando partes y alineándolo con una columna

Sed/awk/perl: modifica el texto conservando partes y alineándolo con una columna

Tengo un texto como este:

A1JOURNEY0TO1
    .BYTE 00, 00, 00
A2JOURNEY0TO2
    .BYTE 00, 01, 00
A3JOURNEY1TO0
    .BYTE 00, 01, 01

Necesito tener:

JOURNEY_01                               ; 00 TO 01
    .BYTE 00, 00, 00
JOURNEY_02                               ; 00 TO 02
    .BYTE 00, 01, 00
JOURNEY_03                               ; 01 TO 00
    .BYTE 00, 01, 01

y así sucesivamente, donde ";" debe estar en el carácter 41 de la línea, y los valores utilizados antes y después de "TO" se toman de las cadenas de texto al inicio de la línea.

Respuesta1

Los detalles de esto dependerán de cuán variable sea su entrada. Si podemos asumir que JOURNEYno cambia y que los números que desea agregar nunca tendrán más o menos dos caracteres ( 01-99), esto funcionará:

perl -pe 's/^.(\d+)      ## ignore the first character and capture 
                         ## as many digits as possible after it.
            (.+?)        ## Capture everything until the next digit: 'JOURNEY'
            (\d+)TO(\d+) ## Capture the two groups of digits on 
                         ## either side of "TO".
            /            ## End match, begin replacement.

            "$2_" .               ## The 2nd captured group, 'JOURNEY'.
            sprintf("%.2d",$1) .  ## The number, 0-padded.
            " " x 31 .            ## 31 spaces.
            sprintf("; %.2d TO %.2d",$3,$4)  ## The start and end, 0-padded.

            /ex;   ## The 'e' lets us evaluate expressions in the substitution
                   ## operator and the 'x' is only to allow whitespace
                   ## and these explanatory comments
        ' file

Lo anterior también se puede condensar en:

perl -pe 's/^.(\d+)(.+?)([\d]+)TO(\d+)/"$2_" . sprintf("%.2d",$1). " " x 31 . sprintf("; %.2d TO %.2d",$3,$4)/e;' file

Si las longitudes de las distintas cadenas también son variables, debes tenerlo en cuenta:

perl -pe 's/^.+?(\d+)(.+?)([\d]+)TO(\d+)/
          "$2_" . sprintf("%.2d",$1) . 
          " " x (41-length(sprintf("%.2d",$1) . "$2_")) . 
          sprintf("; %.2d TO %.2d",$3,$4)/xe;' file  

Respuesta2

Con awk y adivinando lo que deseas

archivo ul.awk (editado)

/JOURNEY/ { jn=substr($1,2,1) ; x=substr($1,10,1) ; y=substr($1,13) ;
    printf "JOURNEY_%02d%s; %02d TO %02d\n",jn,substr("                                        ",1,31),x,y ;
    next ; }
 {print ;}

y luego correr

awk -f ul.awk u

JOURNEY_01                               ; 00 TO 01
    .BYTE 00, 00, 00
JOURNEY_02                               ; 00 TO 02
    .BYTE 00, 01, 00
JOURNEY_03                               ; 01 TO 00
    .BYTE 00, 01, 01

Esta es una codificación algo pobre ya que supuse que el número siempre será de 1 dígito.

información relacionada