Solved Light tweak in batch script for edit text file

September 30, 2019 at 14:15:52
Specs: Windows Vista, r3r3r3
Hello, im a newbie in batch

For this script provided by Mechanix2Go in
https://www.computing.net/answers/p...

What is the way for apply this script in only one line?
For example remove the 190 first characters only in line 47

Any help will be greatly appreciated
Best Regards

--
http://www.heidoc.net/
http://www.vic-fontaine.com/


See More: Light tweak in batch script for edit text file

Reply ↓  Report •

✔ Best Answer
October 1, 2019 at 19:12:29
If you're still listening, here's my version of vbscript in case hackoo's does not work. There was one byte inserted at line 142 (orig. vs edited) which made things more "interesting". I ignored that, concentrating on line 1043 161x removal. The output goes to file "test" with NO SAFETY in place. If this comes anywhere close, maybe we can tweak it to fit. Nothing is impossible!
'begin vbscript "for.vbs"
set fso=createobject("scripting.filesystemobject")
on error resume next
fil=wscript.arguments(0)
if err.number > 0 then
wscript.echo "filename needed"
wscript.quit
end if
on error goto 0
'--------------- FILE READ
'for some reason "readall" does not work - probably char zeros. establish
'a value equal or greater than the file's size for reading
c=fso.getfile(fil).size+10

z=fso.opentextfile(fil,1).read(c)

wscript.echo "size: "&len(z)
p=-1
k=0
'----- do the work
do until k=1042
px=p+2
p=instr(px,z,vbcrlf)
k=k+1
'wscript.echo "k: "&k&" p: "&p
loop
wscript.echo "preparing to cut 161 bytes, line "&p
wscript.echo mid(z,p+2,161)

'============ do the surgery
z=left(z,p+2)&mid(z,p+161)

outfil="test"
fso.opentextfile(outfil,2,true).write z
wscript.echo outfile&" created"
wscript.quit



#1
September 30, 2019 at 17:39:19
You can give a try with this batch code using array
In this code we read our inputfile line by line and we store them into an array,
So it becomes more easy to manipulate with it.
Hope this code can help you !
Have a nice day !
@echo off 
Mode 70,3 & Color 0A
Title Delete 190 first characters at line 47 in a text file
Set "InputFile=%1"
Set "DelChar=190"
If [%InputFile%] EQU [] goto :Help
Set "OutPutFile=%~n0_Output.txt"
If Exist "%OutPutFile%" Del "%OutPutFile%"
echo(
echo                Please be patient ... Working ...
set /a count=0
SETLOCAL enabledelayedexpansion
for /F "tokens=* delims=" %%a in ('Type "%InputFile%"') do (
    Set /a count+=1
    Set "Line[!count!]=%%a"     
)

For /L %%i in (1,1,46) Do (
	echo !Line[%%i]!>>"%OutPutFile%"
)
echo !Line[47]:~%DelChar%!>>"%OutPutFile%"

For /L %%i in (48,1,%count%) Do (
	echo !Line[%%i]!>>"%OutPutFile%"
)

Start "" "%OutPutFile%" & exit
::-----------------------------------------------------------
:Help
Mode 70,3 & Color 0C
echo(
echo      Drag and drop the text file on, this script "%~nx0"
Timeout /T 5 /NoBreak>nul
Exit
::-----------------------------------------------------------

message edited by Hackoo


Reply ↓  Report •

#2
September 30, 2019 at 19:05:35
If you're new to batch, then be advised that textfiles can contain "harbor mines" that will kill your output if you're not careful. Any file with & | < > and ^ can cause unwanted results. The "system" variables: %%a, %1 (as opposed to %a% or %1%) dodge this bullet - they will correctly reflect those "bad" characters EXCEPT for "^". I doubt that this is of interest to you. I'm just posting for posterity (batch will probly be unsupported entirely next couple years anyway). ANYway, that's why this script is written thus:
@echo off
rem 'foo' is your source-file. replace it with yours. From cmd-prompt: foo > fooo
rem I substituted "4" for 47 for obvious testing purpose, and "3" for 190.
rem type foo
rem pause
for /f "tokens=1* delims=[]" %%a in ('find /n /v ""^<foo') do (
if %%a neq 4 (echo]%%b) else call :xx "%%b"
)
goto :eof

:xx
set z=%1
set z="%z:~3%
set z=%z:^^=^%
for /f "tokens=*" %%x in (%z%) do echo %%x
:: note that the "^" needs special handling. good luck! ;)


Reply ↓  Report •

#3
October 1, 2019 at 03:15:55
Here is another approch using a vbscript instead of batch file :
Just copy and paste this code and save it as you want but the extension must be .vbs, and just drag and drop your inputfile over this vbscript to be treated !

Option Explicit
If wscript.Arguments.Count < 1 Then
    Call Display_Help_Usage()
    wscript.Quit(1)
End If

Dim strFile,Contents,arrLines,i,Idx_TargetLine,OutPutFile
Dim Length,sub_str,j,k,Data1,Data2,NewData,Title
Title = "Delete 190 first characters at line 47 in a text file"
Data1 = ""
Data2 = ""
Idx_TargetLine = 47
strFile = wscript.Arguments(0)
OutPutFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "txt"

Contents = ReadFile(strFile,"byline")
Length = Len(Contents(Idx_TargetLine-1))
sub_str = Mid(Contents(Idx_TargetLine-1),190,Length)

For j = LBound(Contents) To Idx_TargetLine - 2
	Data1 = Data1 & Contents(j) & vbCrLF 
Next

For k = Idx_TargetLine To UBound(Contents)
	Data2 = Data2 & vbCrLF & Contents(k) 
Next

NewData = Data1 & sub_str & Data2
Call WriteFileText(OutPutFile,NewData)
MsgBox "Done",vbInformation,Title
'*****************************************************************
Function ReadFile(path,mode)
    Const ForReading = 1
    Dim objFSO,objFile,i,strLine
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile(path,ForReading)
    If mode = "byline" then
        Dim arrFileLines()
        i = 0
        Do Until objFile.AtEndOfStream
            Redim Preserve arrFileLines(i)
            strLine = objFile.ReadLine
            strLine = Trim(strLine)
            If Len(strLine) > 0 Then
                arrFileLines(i) = strLine
                i = i + 1
                ReadFile = arrFileLines
            End If  
        Loop
        objFile.Close
    End If
    If mode = "all" then
        ReadFile = objFile.ReadAll
        objFile.Close
    End If
End Function
'*****************************************************************
Sub Display_Help_Usage()
	Dim ws,Title
	Title = "Delete 190 first characters at line 47 in a text file"
	Set ws = CreateObject("wscript.shell")
	ws.Popup "You should drag and drop a text file over this script " & vbCrLF &_
	chr(34) & WSH.ScriptName & chr(34),8,Title,vbExclamation+vbSystemModal
	Wscript.Quit(1)
End Sub
'*****************************************************************
Function WriteFileText(sFile,Data)
	Const ForAppendig = 8
     Dim objFSO,oTS,sText
     Set objFSO = CreateObject("Scripting.FileSystemObject")
     Set oTS = objFSO.CreateTextFile(sFile,ForAppendig)
     oTS.WriteLine Data
     oTS.close
     set oTS = nothing
     Set objFSO = nothing
 End Function 
 '*****************************************************************


Reply ↓  Report •

Related Solutions

#4
October 1, 2019 at 16:15:22
Thanks for the replys, guys

@nbrane you're right. My file contains special characters, is an RCT file (Generated by RFID reader). If open with notepad appears up to line 1042 plain text, but from line 1043 to end file sometimes appear various special characters (Equivalent to RFID value). I need to delete the first 161 bytes of that line. Maybe it is better to use vbs.

Currently edit all the files in the folder one by one with HxD and I thought that a script could automate this tedious task.. Usually find similar problems and adapt the code for my purpose but this time it's impossible..

I appreciate again the help received, thanks

Pd: For greater understanding attached a link with 2 files, an original file (2 RFID data whith their values) and another edited correctly (1 RFID data whith their values)

https://www.sendspace.com/file/8gbt4h

Best regards

--
http://www.heidoc.net/
http://www.vic-fontaine.com/


Reply ↓  Report •

#5
October 1, 2019 at 19:12:29
✔ Best Answer
If you're still listening, here's my version of vbscript in case hackoo's does not work. There was one byte inserted at line 142 (orig. vs edited) which made things more "interesting". I ignored that, concentrating on line 1043 161x removal. The output goes to file "test" with NO SAFETY in place. If this comes anywhere close, maybe we can tweak it to fit. Nothing is impossible!
'begin vbscript "for.vbs"
set fso=createobject("scripting.filesystemobject")
on error resume next
fil=wscript.arguments(0)
if err.number > 0 then
wscript.echo "filename needed"
wscript.quit
end if
on error goto 0
'--------------- FILE READ
'for some reason "readall" does not work - probably char zeros. establish
'a value equal or greater than the file's size for reading
c=fso.getfile(fil).size+10

z=fso.opentextfile(fil,1).read(c)

wscript.echo "size: "&len(z)
p=-1
k=0
'----- do the work
do until k=1042
px=p+2
p=instr(px,z,vbcrlf)
k=k+1
'wscript.echo "k: "&k&" p: "&p
loop
wscript.echo "preparing to cut 161 bytes, line "&p
wscript.echo mid(z,p+2,161)

'============ do the surgery
z=left(z,p+2)&mid(z,p+161)

outfil="test"
fso.opentextfile(outfil,2,true).write z
wscript.echo outfile&" created"
wscript.quit


Reply ↓  Report •

#6
October 2, 2019 at 17:31:08
Hi, nbrane

First of all I thank you for your time and your patience..
wow, your code is very near to the solution. I don't understand some parts of the code and I don't know where I should touch to adjust to make it work properly. Compare the files (in binary with total commander) generate with you script and file edited and only appear one a difference of 2 bytes (I think from the end of the RFID entry deleted by the script)

Edit: Finally I found the solution ... Changed this value
wscript.echo mid(z,p+2,164)
z=left(z,p+2)&mid(z,p+164)
and remove extra bytes...

Thanks to all the users who answered me and especially to nbrane for providing the code to solve this tedious task.
Thanks..thanks very much

Best regards

--
http://www.heidoc.net/
http://www.vic-fontaine.com/

message edited by 123


Reply ↓  Report •

Ask Question