Sed/awk/perl: 予約された部分のテキストを修正し、列に合わせる

Sed/awk/perl: 予約された部分のテキストを修正し、列に合わせる

次のテキストがあります。

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

以下を行う必要があります。

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

そして、「;」は行の文字41になければなりません。「TO」の前後に使用される値は、行の先頭のテキスト文字列から取得されます。

ベストアンサー1

詳細は、入力がどれだけ変化するかによって異なります。JOURNEYそれが定数であり、ここに追加する数字が2文字()よりも大きいか小さくないと仮定できる場合は、01-99次のように動作します。

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

上記の式は次のように単純化することもできます。

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

さまざまな文字列の長さも可変である場合は、この点を考慮する必要があります。

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  

おすすめ記事