如何将文件中的文本作为标题添加到位于单独文件夹中的多个文件中? [英] How to add text from a file as a header into multiple files which are in separate folder?

查看:145
本文介绍了如何将文件中的文本作为标题添加到位于单独文件夹中的多个文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,里面有一些文本,我需要使用批处理脚本将该文本作为所有文件的标头,这些文件位于不同文件夹中.

I have a text file with some text in it, I need that text to be as header in all the files which are in different folder using batch script.

让我们说Header.txt是文本为This is Heading的文件,我希望该文本作为文件夹C:\...\*.txt的每个文本文件的标题.

Let us say Header.txt is the file with text This is Heading and I want this text to be as heading in each and every text file of the folder C:\...\*.txt.

例如,Body.txt是不同文件夹中的文件之一,其文本为I am the body.我希望Body.txt中的文本为:

For example Body.txt is one of the files in different folder with text as I am the body. I want the text in Body.txt to be as:

This is Heading
I am the body

推荐答案

尝试一下(相应地调整文件名和路径):

Try this (adapt file names and paths accordingly):

for %%F in ("C:\...\*.txt") do (
    > "%%~F.tmp" type "Header.txt"
    >> "%%~F.tmp" type "%%~F"
    move /Y "%%~F.tmp" "%%~F"
)

这会将Header.txt的内容和已处理的文本文件合并到一个临时文件中(例如,文本文件为Body.txt,因此该临时文件为Body.txt.tmp),然后将临时文件移到临时文件上.原始文本文件,因此将其替换.请注意,文件Header.txt中的标题必须以换行符结尾;否则,文本文件的标题和第一行将合并为一行文本.

This combines the content of Header.txt and the processed text file in a temporary file (for instance, the text file is Body.txt, so the temporary file is Body.txt.tmp), then it moves the temproary file over the original text file, hence it get replaced. Note that the heading in the file Header.txt must be terminated with a line-break; otherwise, the heading and the first line of the text file are combined into a single line of text.

为了检查文件是否已将标头插入其中,您可以将其第一行重定向到变量中,并将其与标头文件的第一行进行比较,如下所示:

In order to check the files whether the already have been inserted the header to, you could redirect their first lines into a variable and compare them with the first line of the header file, like this:

< "Header.txt" set /P HEAD=""
for %%F in ("C:\...\*.txt") do (
    < "%%~F" set /P LINE=""
    setlocal EnableDelayedExpansion
    if not "!LINE!"=="!HEAD!" (
        endlocal
        > "%%~F.tmp" type "Header.txt"
        >> "%%~F.tmp" type "%%~F"
        move /Y "%%~F.tmp" "%%~F"
    ) else endlocal
)

在这里单独检查每个文件.为此,您需要延迟扩展,因为您需要在块中写入相同的变量或从中读取相同的变量代码,即for循环.

Every single file is checked individually here. For this you need delayed expansion as you are writing to and reading from the same variable within a block of code, that is the for loop.

这篇关于如何将文件中的文本作为标题添加到位于单独文件夹中的多个文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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