欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

批处理实现文本内容居中显示的代码

程序员文章站 2022-05-26 10:56:39
a.txt   代码: [promise don't come easy] i should have known all along. there was somethi...
a.txt  
代码:

[promise don't come easy]
i should have known all along.
there was something wrong.
i just never read between the lines.
then i woke up one day and found you on your way.
leaving nothing but my heart behind.
what can i do to make it up to you.
promises don't come easy.
but tell me if there's a way to bring you back home to stay.
well i'd promises anything to you.
i've been walkin' around with my head hanging down.
wondrin' what i'm gonna do.
'cause when you walked out that door.
要求,cmd原始窗口中,不调节窗口大小,不生成临时文件,居中显示文本内容。输出如下:
代码:


[promise don't come easy]
i should have known all along.
there was something wrong.
i just never read between the lines.
then i woke up one day and found you on your way.
leaving nothing but my heart behind.
what can i do to make it up to you.
promises don't come easy.
but tell me if there's a way to bring you back home to stay.
well i'd promises anything to you.
i've been walkin' around with my head hanging down.
wondrin' what i'm gonna do.
'cause when you walked out that door.

batcher:

sed -e :a -e "s/^.\{1,77\}$/ & /;ta" a.txt

sed.exe
 

batman:思路说明:
以下代码是充分findstr命令的示例,使用findstr /n来取得行号同时兼容空行,
并将行号进行变量赋值;使用findstr /o来取得第行的字符偏移量,但要通过
上、下行的字符偏移差,因为字符偏移值是类计递加的,同时每行回车增加
两个字符偏移,所以不可避免要对最后一行强加回车,在不破坏原文件的情
况下只好生成临时文件;利用findstr /o能够一次性获得文本所有行的字符偏
移量也就是字符总数,效率和逐字符判断相比肯定是高得多了。
---------------------------------
复制代码 代码如下:

@echo off
copy /y 1.txt 2.txt>nul
echo.>>2.txt&echo end>>2.txt
for /f "tokens=1,2* delims=: " %%i in ('findstr /n /o .* 2.txt') do (
set "_%%i=%%j"&set ".%%i=%%k"
  if %%i geq 2 call :lp %%i
)
del /q 2.txt&pause>nul&goto :eof
:lp
set /a n=%1-1
set /a num=_%1-_%n%-2
set /a kl=(80-num)/2
for /l %%i in (1,1,%kl%) do set /p= <nul
call,set /p=%%.%n%%%<nul&echo.