I have a text file, I was wondering anyone have a batch file to add \" to the beninning and \", at the end of each line in a text file?
For example I have
set "f=PATH\FILE.txt"
call :add_str_beginning_end_each_line "BEGIN_LINE--" "--END_LINE" "%f%"
REM : Adds strings at the beginning and end of each line in file
:add_str_beginning_end_each_line
set "str_at_begining=%~1"
set "str_at_end=%~2"
set "input_file=%~3"
set "tmp_file=tmp.ini"
REM : >NUL => copy command is silent
REM : Make a backup
copy /Y "!input_file!" "!input_file!.bak" >NUL
copy /Y "!input_file!" "!tmp_file!" >NUL
del "!input_file!"
REM : Add strings at each line
for /f "delims=" %%a in (!tmp_file!) do (
>>"!input_file!" echo !str_at_begining!%%a!str_at_end!
)
REM : delete backup
del "!tmp_file!"
del "!input_file!.bak"
REM : exiting the function only
EXIT /B 0
You can edit the code :
"!input_file!" echo !str_at_begining!%%a!str_at_end!
By removing !str_at_end! to add str only at the beginning of the line, where %%a is the actual line.
@echo off
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (input.txt) do (
set /a N+=1
echo ^"%%a^",>>output.txt
)
-joedf
The script uses a FOR
loop count the # of lines, and FOR /L along with SET /P
to read the file line-by-line:
@echo off
SETLOCAL EnableDelayedExpansion
::Initialize SUB character (0x1A)
>nul copy nul sub.tmp /a
for /F %%S in (sub.tmp) do set "sub=%%S" SUB CHARACTER
::Variables
;set "lines=-1" Exclude LAST line
set "in=<CHANGE THIS>"
set "out=text.txt"
::Count lines
FOR /F tokens^=*^ delims^=^ eol^= %%L in (
'2^>nul findstr /N "^" "%in%"'
) do set /a "lines+=1"
::Read file using SET /P
>newline.tmp <"!in!" (
for /L %%a in (1 1 %lines%) do (
set "x=" For EMPTY lines
set /p "x="
echo("!x!",
)
;set "x="
;echo("!x!",!sub!
)
::Trim trailing newline appended by ECHO
;copy newline.tmp /a "!out!" /b
;del sub.tmp newline.tmp
The foolproof way of counting the number of lines is explained in this answer.
Takes advantage of the SUB
character (0x1A) to trim trailing newlines, discussed here on DosTips. If you don't want to trim them, just comment out the lines that start with ;
.
Off the top of my head, in Linux, you can...
$ for each in `cat filename` ; do echo \"$each\", ; done >> newfilename
"1",
"2",
"3",
"4",
"5",
Edited - since it's for Windows, this did the trick for me:
@echo off
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (filename.txt) do (
echo "%%a", >>newfilename.txt
)