I need a batch file that will add the text \"Write In\" in a new line at the beginning of the content of hundreds of .txt files without removing any existing text. I found somet
I would most probably do it like this:
rem // Create temporary header file:
> "head.txt" echo Write In
rem // Iterate all text files in current directory:
for %%F in ("*.txt") do (
rem /* Combine header and currently iterated text file into a temporary file;
rem there cannot arise any file name conflicts (like temporary files becoming
rem iterated also unintendedly, or temporary files overwriting files to handle),
rem because the extension of the temporary files differ from the text files: */
copy /B "head.txt"+"%%~F" "%%~F.tmp"
rem // Overwrite original text file by temporary file, erase the latter:
move /Y "%%~F.tmp" "%%~F"
)
rem // Erase the temporary header file:
del "head.txt"
I found a way that is not very clean and will take a while for bigger files, but it works out for me:
@echo off
for /r "%~dp0" %%f in (*.txt) do (
echo Processing file %%f
>"%%~f.2" (
echo "Text to append here"
type "%%~f"
)
del "%%~f"
ren "%%~f.2" "%%~nxf"
)
pause
Loops recursively through all .txt
-files in the batch-files directory.
Creates a new file with the name oldName.txt.2
and files it with the text to add and the rest of the oldfiles content.
Deletes the old file and renames the new file to the name of the old one.
The addition of .2
to the file ending is needed to make sure it does not get processed again by the loop.
Of course you can add multiple lines by multiplying the echo lines.
You can as well add text to the end of the file like this with adding the echo lines after the type
line.
You can simply use the Linux Sed
command to insert a header into a file.
sed -i '1s/^/This is my header\n/' filename
e.g. sed -i '1s/^/Write In\n/' myfile.txt
This can be applied to multiple files under a directory:
For .txt files
for file in *.txt
do
sed -i '1s/^/This is my header\n/' $file
done
For CSV files
for file in *.csv
do
sed -i '1s/^/This is my header\n/' $file
done