Edit text file with batch file under Windows - windows

I've got an issue regarding a text file I'd like to change with a batch file. I was able to trim it to this point.
3539
78060031
523 )
What I need now is to get the numbers in the same line. By the way the text file is not written by my programm. What I need is now to get some backspaces till it looks like this:
353978060031523
I know there is a simple solution, but since I'm very bad in scripting I can't
find it.
Sorry for my bad english and the bad post!
It's the first time I post something here.
Thank you in advance.

This is a duplicated question. But, well, nevermind, I just answer your question.
I don't know what's the purpose of a ")" behind the "523", but since you're just concatenate the string, try out the following script:
#echo off
setlocal EnableDelayedExpansion
for /f "tokens=*" %%a in (hxh-chp.txt) do (
set "concatenate_string=!concatenate_string!%%a"
)
echo !concatenate_string!
pause >nul

The following should do what you expect, that is, concatenate the numerical characters and removing all spaces and the ):
setlocal EnableDelayedExpansion
for /F "usebackq" %%L in ("\path\to\your\text_file.txt") do (
set "CONCAT=!CONCAT!%%L"
)
endlocal & set "CONCAT=%CONCAT%"
echo %CONCAT%
This code makes use of the default behaviour of for /F, where the option tokens=1 and delims is tab and space.

Related

Batch file to write for-variables into other files

I am trying to write a batch file that will create other, more complex batch files.
This is a portion of my script for right now:
(
echo #echo off
echo for /f "delims=" %%a in (themeset.txt) do set color=%%a&goto setcolor
echo :setcolor
echo color %%color%%
echo pause
) >otherfile.cmd
Theoretically, the output should be a .cmd file with these exact contents:
#echo off
for /f "delims=" %%a in (themeset.txt) do set color=%%a&goto setcolor
:setcolor
color %color%
pause
However, the batch file does not run, and when I attempted to double the %% signs it does not write the entire line correctly.
Any suggestions or solutions would be appreciated.
Max
Magoo's comment beat me to most of the issues.
There is a mostly obscure situation where ECHO text to echo fails, so many people switched to ECHO.text to echo. But somewhere along the way I hit an even more obscure line where that failed, and discovering that semicolon didn't have that problem, I switched to ECHO;text to echo. Which so far, I've not seen any issues.
The FOR /F command has issues, with EOL defaulting to the semicolon being one of them. Some web-page out there made the claim that DELIMS was executed before EOL, so setting EOL to the same as DELIMS would disable it. In my testing it does. But now if we want the whole line, it seems that TOKENS=* disables DELIMS. As far as I know, this is true, but I will admit that I haven't tested that one as much as I would like, so it is probably best to set DELIMS=~, or to similar character that isn't likely to be found in the file.
The % has to be escaped with another percent as in %%, but FOR requires %%, so now you need 4 percents %%%% total.
%%~aa, %%~dd, %%~ff, %%~nn, %%~pp, %%~ss, %%~tt, %%~xx, and %%~zz are all ambiguous. So it probably best to use only capital letters with FOR variables, and probably safest to use only these letters: %%B, %%C, %%E, %%G, %%H, %%I, %%J, %%K, %%L, %%M, %%O, %%Q, %%R, %%U, %%V, %%W, and %%Y See the bottom sections of the help produced by FOR /? for more info on this.
Use the caret to escape special characters. This page, Escape using caret(^), gives some useful info, but its NOT complete. You NEED the caret before the closing parentheses ^), which that page fails to tell you. And to play it safe, I also caret the opening parentheses ^(. But the good thing about that page is that it does points out that when DelayedExpansion is on, you have to double escape the exclamation mark ^^!.
Most of the rest is conventions, I normally capitalize all commands and place a colon in front of all labels, both GOTO :Label and CALL :Label.
The following code:
#ECHO OFF
(
ECHO;#ECHO OFF
ECHO;FOR /F "EOL=~ TOKENS=* DELIMS=~" %%%%L IN ^(themeset.txt^) DO SET Color=%%%%L^&GOTO :SetColor
ECHO;:SetColor
ECHO;Color %%Color%%
ECHO;PAUSE
) >otherfile.cmd
Producted the following file:
#ECHO OFF
FOR /F "EOL=~ TOKENS=* DELIMS=~" %%L IN (themeset.txt) DO SET Color=%%L&GOTO :SetColor
:SetColor
Color %Color%
PAUSE
It is clear from your code that you are not even performing the task in the most efficient manner. The following example will therefore perform the same task, but using another methodology. (i.e. retrieve the first line of the text file content and use it as the color command parameter from another Windows Command Script)
#( Echo #Set /P "colr=" 0^< "themeset.txt"
Echo #Color %%colr%%
Echo #Pause) 1> "otherfile.cmd"

Extracting URL from text file in Batch

I have a script that needs to extract a YouTube URL from a text file.
Here's what I have in the text file (output.txt):
---------- NUMBER11.TXT
<link itemprop="url" href="http://www.youtube.com/channel/UCnxGkOGNMqQEUMvroOWps6Q">
Note the text file has a line of empty space to start, which is annoying, and the URL is on line 3. Something that doesn't show up in the formatting for this site is the 11 spaces before the actual href starting as well. I'd like to separate it from the mass of other junk.
I've tried something like this:
set /p long= < output.txt
echo %long%
set short1=%long:^<link itemprop^="url" href^="=%
echo %short1% > o1.txt
I thought this would remove the selected text from the file, but I think this is a little over my head.
I'm getting the output.txt from firstly a curl of a youtube video page, and secondly from a find command here:
find "href=""http://www.youtube.com/channel/" %vd% > output.txt
Maybe I'm making this more complicated than it is?
Using batch-files to access files with special characters, like redirect, it can cause some problems, so it is not recommended, but I felt like posting an answer anyway, so given you exact example, here is one way. If your example is not as per your post, which I highly expect it to be, then this probably would not work.
#echo off
setlocal enabledelayedexpansion
for /f "usebackq delims=" %%i in ("output.txt") do for %%a in (%%i) do (
set "var=%%~a"
set "var=!var:>=!"
set "var=!var:"=!"
if "!var:~0,4!" == "http" echo !var!
)
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q64572433.txt"
set "url="
FOR /f "tokens=4,5delims=>= " %%a IN (%filename1%) DO if "%%~a"=="href" set "url=%%~b"
echo URL=%url%
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances. The listing uses a setting that suits my system.
I used a file named q64572433.txt containing your data for my testing.
The for command tokenises each line of the file, using =, > and space as delimiters (the 3 characters between delims= and ")
On the line of interest, token 4 would be href and token 5 the url - and this is the only line where href is the fourth token. When that is detected, assign the 5th token (in %%b) to the variable, removing the quotes with ~ for good measure.
I would suggest you parse the results directly from your curl command instead of outputting them to a text file, and then using find against that output.
However, instead of using find.exe, I would suggest you use the following method using findstr.exe instead, to get the URL assigned to any line containing href= followed by "http: or "https and subsequently followed by youtube.com.
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
For /F Tokens^=*EOL^= %%G In (
'%__APPDIR__%findstr.exe /IR "href=\"http[s:].*youtube\.com" "output.txt"'
) Do (Set "Line=%%G" & SetLocal EnableDelayedExpansion
For /F Tokens^=2Delims^=^" %%H In ("!Line:*href=!") Do EndLocal & Echo %%H)
Pause
If you want the output stored as a variable, instead of Echoing it, change Echo %%H to Set "URL=%%H". You could then use %URL%, (or "%URL%" if you need it doublequoted), elsewhere in your script.

How to keep first 50 characters of a filename in prompt Windows

I'm writing to you because I need to create a batch file that allows me to rename many files in .pdf keeping only the first 50 characters.
I've tried this:
for %i in (*.txt) do (set fName=%i)
ren %fName% %fName:~0,-11%.txt
But this removes only the last 11 characters.
I've tried to modify this code but I can in no way do what I need.
I think it's a very easy thing for someone who is a little more expert than me so I ask you if you can help me.
Thanks in advance.
I insert below the errors that come to me following the corrections:
C:\Users\---\Desktop\Conversione PDFA>for %fname:~0,50% in (*.pdf) do (set fname=%~ni)
graeiojpoghnpiofsdnpibnwapobnslnsdlekpfèwekrgpjbm was unexpected at this time.
C:\Users\---\Desktop\Conversione PDFA>for %fname:~0,50% in (*.pdf) do (set fname=%~ni)
graeiojpoghnpiofsdnpibnwapobnslnsdlekpfèwekrgpjbm was unexpected at this time.
C:\Users\---\Desktop\Conversione PDFA>for %fname:~0,50% in (*.pdf) do (set fname=%i)
graeiojpoghnpiofsdnpibnwapobnslnsdlekpfèwekrgpjbm was unexpected at this time.
C:\Users\---\Desktop\Conversione PDFA>ren %fName% !fname:~0,50!.pdf
The syntax of the command is incorrect.
C:\Users\---\Desktop\Conversione PDFA>ren %fName% %!fname:~0,50!.pdf
The syntax of the command is incorrect.
for %fname:~0,50% ...: just no.
for %i in (*.pdf) do set fname=%i: yes.
You want to rename several PDF's, so the ren command should be within the loop. That's possible but ugly and error-prone (especially when you are not (yet) firm in cmd syntax) in a single command line, so I wouldn't' suggest it. Your best approach is the use of a batch file. It's much more readable and maintainable.
#echo off
setlocal enabledelayedexpansion
for %%i in (*.pdf) do (
set "fname=%%~ni"
ECHO ren "%%~fi" "!fname:~0,50!%%~xi"
)
See for /? for an explanation of the modifiers %%~ni etc.
See delayed expansion for the usage of !fname! instead of %fname%
NOTE: I "disarmed" the ren command for security reasons by just echoing it. When you have verified, it's exactly what you want, just remove the ECHO

how to replace one line in text file without removing empty lines in batch

i am trying to code a simple script in batch that can find and replace a line
so far, I've found a snippet that works perfectly fine for my purpose the only problem is that it removes empty lines
and i can't figure out why!!
I've tried to add another if statement in this for loop but I fail
also I found that there is a bat called JREPL, i tried to run few simple commands from the docs and i failed again XD
here is the snippet:
:Variables
set InputFile=t.txt
set OutputFile=t-new.txt
set _strFind= old "data"
set _strInsert= new "data";
:Replace
>"%OutputFile%" (
for /f "usebackq delims=" %%A in ("%InputFile%") do (
if "%%A" equ "%_strFind%" (echo %_strInsert%) else (echo %%A)
)
)
i was expecting that this snippet won't remove my empty lines
and i can't figure out why
I am posting this without testing, as I do not have the environment to test as we speak.
But to explain your issue, cmd will ommit empty lines as it is built that way. It is the same as setting a variable to nothing and expecting it to return a result, so we simply assign values to each line by sort of simulating a detection of line breaks (Don't know exactly how to explain that one) but nevertheless, we will add some additional characters to the lines to ensure we get line breaks, the just get rid of them once we have them, So here goes:
#echo off
setlocal enabledelayedexpansion
set inputfile=t.txt
set outputfile=t-new.txt
set _strfind=old "data"
set _strinsert=new "data";
for /f "tokens=*" %%a in ('type "%inputfile%" ^| find /v /n "" ^& break ^> "%inputfile%"') do (
set "str=%%a"
set "str=!str:*]=!"
if "!str!"=="%_strfind%" set "str=%_strinsert%"
>>%outputfile% echo(!str!
)
That should send to output file.. You can however make the output file the same as the input as it would then be the same as replacing the text inline in the original file. Once I am able to test, I will fix the answer if there are any issues with it.
As a side note, be careful of where you have additional whitespace in your variables you set. For instance:
set a = b
has 2 issues, the variable, containing a space after a will be created with the space. So it will be seen as:
%a %
The aftermath of this is that the value of the variable will start with a leading space, so when you expected b as the value, it in fact became b
Then lastly, it is alsways a good idea to enclose your variables with double quotes, simply again to eliminate whitespace, because:
set a=b
Even though you cannot see it with your naked eyes, contains a space at the end, so doing a direct match like:
if "b"=="b"
Will result in a false statement as in fact we have:
if "b"=="b "
So the correct statement would be to set variables as:
set "a=b"
if "%a%"=="b"
which will be a perfect match.
Note I posted this from my phone, so any spelling, grammar and code issues I will resolved as I go though my answer.
…and one way using JREPL
JRepl "old \qdata\q" "new \qdata\q;" /I /XSEQ /F "t.txt" /O "t-new.txt"

Parsing filename from text file gives the wrong details

Please note I'm new to scripting so please be gentle!
I have a text file called list.txt with just one line (for testing), the line is:
D:\italy\gfm\users\test\avisgfm_1001_1500.txt
My script is:
#echo off
for /f "delims=" %%1 in (list.txt) do (
echo %%~1
echo %%~d1
echo %%~p1
echo %%~n1
echo %%~x1
)
However the result from the script is:
´╗┐d:\italy\gfm\users\test\avisgfm_1001_1500.txt
C:
\PCI\´╗┐d:\italy\gfm\users\test\avisgfm_1001_1500.txt
Any idea whats going on? I'm doing this via a Windows Batch file.
Thanks
The metavariable should be a (case-sensitive) letter.
Numbers refer to parameters to the routine.
for /f "delims=" %%a in (list.txt) do (
echo %%~a
and so on will work fine.
It seems you've saved list.txt with some encoding like UTF-8 with byte order mark at the head of file. BAT can process only ASCII text files. Try to create list.txt as simple ASCII text file. Notepad form Windows can do that.
%%1 works fine but it's better to use letter, for example %%i, as in for spec.

Resources