gpt4 book ai didi

batch-file - 在 Windows 中,是否可以编写一个模拟 findstr/n/r 的批处理。文件.txt?

转载 作者:行者123 更新时间:2023-12-02 02:50:42 25 4
gpt4 key购买 nike

好吧,我知道这纯粹是学术性的,因为 findstr 命令可以立即完成我所期望的事情。

我有一个文本文件,我想要对其字符串(行)进行编号。我想知道是否可以编写一个批处理来模拟它,并让我能够灵活地将标记整数移动到字符串中的任何位置。

例如标准输出是1: some string

让我们说我想要

  • 1)一些字符串 (不使用 Windows 资源管理器中的查找和替换),或
  • 某个字符串......(1),或
  • s 1] 一些字符串

最佳答案

编辑:我修改了代码以便在行中的任何位置插入行号:

@echo off
setlocal DisableDelayedExpansion

rem Define the format of output lines; for example

rem To show "(lineNo) line" use:
set "format=(!lineNo!) !line!"

rem To show "20 chars of line (lineNo) rest of line" use:
set "format=!line:~0,20! (!lineNo!) !line:~20!"
rem and adjust each line read appending 20 spaces

rem To show "line (lineNo placed at column 75)" use:
set "format=!line:~0,73! (!lineNo!)"
rem and adjust each line read appending 73 spaces

rem To show line numbers with left zeros, start lineNo with the proper
rem number of zeros and modify the format accordingly; for example:
set lineNo=100
set "format=!line:~0,73! (!lineNo:~1!)"


setlocal EnableDelayedExpansion
copy %1 "%~1.tmp" > NUL
set "EOF=%random%%random%%random%"
echo :%EOF%EOF:>> "%~1.tmp"
REM set lineNo=0
call :ReadLines < "%~1.tmp"
del "%~1.tmp"
goto :EOF

:ReadLines
set "line="
set /P "line="
if "!line!" equ ":%EOF%EOF:" goto :EOF
set "line=!line! "
set /A lineNo+=1
echo %format%
goto ReadLines

输出示例:

@echo off                                                                 (01)
setlocal DisableDelayedExpansion (02)
(03)
rem Define the format of output lines; for example (04)
(05)
rem To show "(lineNo) line" use: (06)
set "format=(!lineNo!) !line!" (07)
(08)
rem To show "20 chars of line (lineNo) rest of line" use: (09)
set "format=!line:~0,20! (!lineNo!) !line:~20!" (10)
rem and adjust each line read appending 20 spaces (11)
(12)
rem To show "line (lineNo placed at column 75)" use: (13)
set "format=!line:~0,73! (!lineNo!)" (14)
rem and adjust each line read appending 73 spaces (15)
(16)
rem To show line numbers with left zeros, start lineNo with the proper (17)
rem number of zeros and modify the format accordingly; for example: (18)
set lineNo=100 (19)
set "format=!line:~0,73! (!lineNo:~1!)" (20)
(21)
(22)
setlocal EnableDelayedExpansion (23)
copy %1 "%~1.tmp" > NUL (24)
set "EOF=%random%%random%%random%" (25)
echo :%EOF%EOF:>> "%~1.tmp" (26)
REM set lineNo=0 (27)
call :ReadLines < "%~1.tmp" (28)
del "%~1.tmp" (29)
goto :EOF (30)
(31)
:ReadLines (32)
set "line=" (33)
set /P "line=" (34)
if "!line!" equ ":%EOF%EOF:" goto :EOF (35)
set "line=!line! (36)
set /A lineNo+=1 (37)
echo %format% (38)
goto ReadLines (39)

关于batch-file - 在 Windows 中,是否可以编写一个模拟 findstr/n/r 的批处理。文件.txt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31635408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com