This page is edited from the 1cmdfaq.txt faq-file contained in
my tscmd.zip
command line interface (CLI) collection. That zipped file has much
additional material, including a number of detached .cmd script
files. It is recommended that you also get the zipped version as a
companion.
Please see "
The Description and
the Index page" for the conditions of usage and other such
information.
65} How do I add text in front and after each line in a text file?
Assume the following LFN-type test file: "My test file.txt"
line 1
line 2 &()[]{}^=;!'+,`~
line 3 <>
line 4
line 6 Line 5 is empty!
With pure script, but skipping any empty lines!
@echo off & setlocal enableextensions
for /f "delims=" %%r in ('type "My test file.txt"') do (
echo Add in front%%radd after)
endlocal & goto :EOF
The output will be
Add in frontline 1add after
Add in frontline 2 &()[]{}^=;!'+,`~add after
Add in frontline 3 <>add after
Add in frontline 4add after
Add in frontline 6 Line 5 is empty!add after
Note how this at the same time answers the question how to remove
empty lines from a text file.
With SED
@echo off & setlocal enableextensions
<"My test file.txt" sed -e "s/.*/Add in front
&add after/"
endlocal & goto :EOF
The output will be
Add in frontline 1add after
Add in frontline 2 &()[]{}^=;!'+,`~add after
Add in frontline 3 <>add after
Add in frontline 4add after
Add in frontadd after
Add in frontline 6 Line 5 is empty!add after
With
G(nu)AWK
@echo off & setlocal enableextensions
<"My test file.txt" gawk '{printf "Add in front%%sadd after\n",$0}'
endlocal & goto :EOF
A Visual Basic Script (VBScript) aided command line script version
@echo off & setlocal enableextensions
::
:: Build a Visual Basic Script
set skip=
set vbs_=%temp%\tmp$$$.vbs
findstr "'%skip%VBS" "%~f0" > "%vbs_%"
::
:: Run the script with Microsoft Windows Script Host Version 5.6
cscript //nologo %vbs_% "Add in front" "add after"< "My test file.txt"
::
:: Clean up
for %%f in ("%vbs_%") do del %%f
endlocal & goto :EOF
'
'.......................................................
'The Visual Basic Script
'
before = WScript.Arguments.Unnamed(0) 'VBS
after = WScript.Arguments.Unnamed(1) 'VBS
Do While Not WScript.StdIn.AtEndOfStream 'VBS
str = WScript.StdIn.ReadLine 'VBS
WScript.StdOut.WriteLine before & str & after 'VBS
Loop 'VBS