smace
smace

Reputation: 1178

Add chararacter to end of each lines except the last one

I'm trying to convert a file containing json line into a json array. To achieve this I had to append opening and closing square brackets to the file (which is done!). To finish I just need to append a comma to the end of each line except the last one. I'm using the following script, but I don't how to stop at the last line.

@echo off
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (input.txt) do (
set /a N+=1
echo ^%%a^, >> output.txt
)

Thank you by advance for any help!

Upvotes: 3

Views: 214

Answers (3)

dbenham
dbenham

Reputation: 130929

Editing text files with pure batch can be done, but it takes an unreasonable amount of code, especially if you want the result to be robust. And it tends to be slow for large files.

As with most any problem where I want to manipulate the content of a file in batch, I would use JREPL.BAT - a regular expression find and replace utility.

JREPL.BAT is pure script (hybrid JScript/batch) that runs natively on any Windows machine from XP onward. Full documentation is available from the command line via jrepl /?, or jrepl /?? if you want paged output.

JREPL is extremely powerful and reasonably fast. However, you do need to understand regular expressions, and if you study the many JREPL options, then you can do some really sophisticated things efficiently.

The following will append an X to every line except the last one.

jrepl "\r?\n(?=[\s\S])" "X$&" /m /f test.txt /o -

Use call jrepl if you put the command within a batch script.

The above will work with any text file, as long as it is less than 1 gigabyte in total length. This limitation stems from the fact that you must use the /M option to search across multiple lines. So the entire file must be loaded into memory, and JScript limits the memory size.

Upvotes: 1

Aacini
Aacini

Reputation: 67326

@echo off
setlocal EnableDelayedExpansion

set "line="
(  for /F "delims=" %%a in (input.txt) do (
      if defined line echo !line!,
      set "line=%%a"
   )
   echo !line!
) > output.txt

Upvotes: 1

npocmaka
npocmaka

Reputation: 57332

Try this , Should work if your lines does not content ! symbols. It will produce a temp.file .If the file is what you need remove the last line.You'll need to change the values of fileLoc and endSymbol with the values you want.

@echo off
setlocal enableDelayedExpansion

::-------------------------::
:: Change the values here  ::
set "fileLoc=testFile.txt"
set "endSymbol=,"
::-------------------------::



set counter=0
for /f "usebackq tokens=* delims=" %%# in ("%fileLoc%") do (
    set /a counter=counter+1
    set "line[!counter!]=%%#"
)

set /a upToLine=counter-1
break>temp.file
for /l %%# in (1;1;!upToLine!) do (
    (echo(!line[%%#]!%endSymbol%)>>temp.file
)
(echo(!line[%counter%]!)>>temp.file

:: Uncoment line bellow if temp.file is ok
rem move /y temp.file "%fileLoc%"

Upvotes: 2

Related Questions