我有這樣的文字:
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 位數字。