批处理脚本替换括号 [英] Batch script to replace parentheses

查看:121
本文介绍了批处理脚本替换括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.txt文档,其中包含超过32,000行带注释的机器代码.看起来像这样:

I have a .txt document with over 32,000 lines of commented machine code. It looks like this:

; Display menu window
C0/000E:    E220        SEP #$20       (Set 8-bit accumulator)
C0/0010:    C210        REP #$10       (Set 16-bit X and Y)

出于编译目的,我需要按以下方式转换注释:

I need to convert the comments as follows for compiling purposes:

; Display menu window
C0/000E:    E220        SEP #$20       ; Set 8-bit accumulator
C0/0010:    C210        REP #$10       ; Set 16-bit X and Y

具体来说,这意味着:

  • 如果该行不是以"C0/"开头,则不执行任何操作.
  • 如果第34个字符不是左括号,则该行可能仅包含数据,所以什么也不做.
  • 如果是左括号,则将其替换为分号和空格
  • 然后,找到并删除右括号.最好是,如果在同一行上都找不到,则应该放弃,但这不是必须的.

请注意,此面板用许多空格替换了制表符,因此左括号不会成为您的第34个字符.

Note that this board replaces tabs with a number of spaces, so the opening parenthesis won't appear to be the 34th character to you.

理想情况下,我想要一个批处理脚本,该脚本允许我拖放文档(例如abc.txt),并自动获取其他文件(例如abc2.txt).但这不是强制性的.

Ideally, I'd like a Batch script that allows me to drag-and-drop a document (e.g., abc.txt), and automatically get a different file (e.g., abc2.txt). But that's not mandatory.

必须强调的是,代码本身可以包含括号,因此不能选择简单的查找和替换.示例:

It has to be stressed that the code itself can contain parentheses, so a simple find-and-replace is not an option. Example:

C0/0000:    7C0600      JMP ($0006,X)  (Display window X)

推荐答案

第一部分是提取提取到蝙蝠的文件,生成输出名称并整理目标文件.

The first part is about extracting the file dropped to your bat, generating the output name and clering the target file.

在代码的第二部分中,我们将逐一检查您的条件,并仅在所有条件都适合当前行时执行替换.

In the second part of the code we are checking for your criteria one by one and performing the replacement only if all of them fit to the current line.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET source=%1

FOR /F "tokens=1 delims=." %%t IN ("%source%") DO SET target=%%t
SET target=!target!2.txt
TYPE NUL>!target!

FOR /F "tokens=1* delims=]" %%j in ('type "%source%" ^| find /V /N ""') DO (
    IF "%%k"=="" (
        ECHO.>>!target!
    ) ELSE (
        SET currentLine=%%k
        IF "!currentLine:~0,2!"=="C0" (
            IF "!currentLine:~34,1!"=="(" (
                SET left=!currentLine:~0,33!
                SET right=!currentLine:~34!
                ECHO !right!
                SET right=!right:(=; !
                SET right=!right:^)=!
                ECHO !right!
                SET currentLine=!left!!right!
            )
        )
        ECHO !currentline!>>!target!
    )
)

正如您所提到的,在解释制表符和空格时可能会出现问题.就我而言(我已经从您的帖子中复制了您的输入文件),我必须使用以下方法:

As you've mentioned there might be a problem interpreting tabs and spaces. In my case (I've copied your input file from your post) I had to use this:

...
IF "!currentLine:~39,1!"=="(" (
    SET left=!currentLine:~0,38!
    SET right=!currentLine:~39!
...

这篇关于批处理脚本替换括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆