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변하지 않고 여기에 추가하려는 숫자가 두 문자( )보다 크거나 작을 수 없다고 가정할 수 있다면 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  

답변2

awk를 사용하여 원하는 것이 무엇인지 추측

파일 ul.awk (편집됨)

/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 ;}

그런 다음 실행

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

숫자가 항상 1자리라고 가정했기 때문에 이는 다소 잘못된 코딩입니다.

관련 정보