【问题标题】:How to write the name of the text file into the text file using bat?如何使用bat将文本文件的名称写入文本文件?
【发布时间】:2014-04-18 10:05:49
【问题描述】:

我有问题。我有很多文本文件(.txt)。我想在里面写下相应文本文件的名称,最后合并它们。我有很多。手动不行,太费时间了。

假设,我有一个名为“windows.txt”的文本文件,其内容是

Windows XP
Windows 7
Windows 8

我希望他们的内容是

windows
Windows XP
Windows 7
Windows 8

合并相似文件后,它们应该看起来像

windows
Windows XP
Windows 7
Windows 8

continents
Europe
Asia
Africa

languages
English
Chinese

请帮忙!!

【问题讨论】:

  • type *.txt >final.txt 做你想做的事吗?
  • 上述命令只合并它们。我还需要里面对应的.txt文件的名称
  • @npocmaka 向您展示如何将文件名包含到生成的文件中。您真的需要将文件名写入单个文件吗?

标签: batch-file merge filenames


【解决方案1】:
@echo off
echo. >result
for /f %%i in ('dir /b /a-d *.txt') do (
 echo.
 echo %%~ni
 type %%i
)>>result
ren result result.txt

为了更好理解的伪代码:

turn echo off
delete result file
for all txt files in current directory do:
 print empty line
 print name of textfile without extension
 print textfile
and put it into new file "result"
if done, rename the resulting file

【讨论】:

  • 我应该怎么做才能在 文本文件的名称 开头打印像 $$ 这样的常量字符串,例如。 $$ 名称
  • 找到写入文件名的行(它是echo %%~ni)并将您的字符串添加到其中:echo $$ %%~ni
【解决方案2】:

可能太容易了,但我认为这是有效的答案:

type *.txt >result 2>&1
ren result result.txt

诀窍是当type 与文件列表或通配符一起使用时,它会在错误流中打印文件名。并且它不会重定向到带有txt 扩展名的文件以避免它的打印,但在最后被重命名。

关于写入其中的文件的名称(最好先测试一下)

@echo off
for %%a in (*.txt) do ( 
 type %%~na.txt* >%%~na 2>&1
 del  /q /f %%~na.txt
 ren %%~na %%~na.txt
 )

编辑

如果启用 8.3 表示法,可能会起作用:

@echo off
ren ????????.txt ???????? >nul 2>&1
for /f "tokens=* delims=" %%# in ('for %%a in (????????^) do @echo %%a') do ( 

 echo %%#>%%~#_
 rem echo %%~n#_
 type %%~n# >>"%%~#_" 2>nul
 del  /q /f "%%~n#"
 ren "%%~n#_" "%%~n#.txt"
)

【讨论】:

  • 它完全有效,但文件名后有两个返回(输入)。并请删除文件打印名称后的.txt
猜你喜欢
  • 2013-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-31
  • 1970-01-01
  • 2019-01-15
相关资源
最近更新 更多