How to find string in .txt file using regex? [closed] - batch-file

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I would like to find: 9ozrhtdy1uq31 in this single line text file:
[{"kind": "Listing", "data": {"modhash": "", "dist": 1, "children": [{"kind": "t3", "data": {"approved_at_utc": null, "subreddit": "blackmagicfuckery", "selftext": "", "user_reports": [], "saved": false, "mod_reason_title": null, "gilded": 0, "clicked": false, "title": "Electron-filled acrylic cylinder at my work. Sorry for the dark video", "link_flair_richtext": [], "subreddit_name_prefixed": "r/blackmagicfuckery", "hidden": false, "pwls": 6, "link_flair_css_class": null, "downs": 0, "thumbnail_height": 140, "parent_whitelist_status": "all_ads", "hide_score": false, "name": "t3_ddxfse", "quarantine": false, "link_flair_text_color": "dark", "upvote_ratio": 0.98, "author_flair_background_color": null, "subreddit_type": "public", "ups": 16387, "total_awards_received": 1, "media_embed": {}, "thumbnail_width": 140, "author_flair_template_id": null, "is_original_content": false, "author_fullname": "t2_wk8jx", "secure_media": {"reddit_video": {"fallback_url": "https://v.redd.it/9ozrhtdy1uq31/DASH_1080?source=fallback", "height": 1080, "width": 608, "scrubber_media_url": "https://v.redd.it/9ozrhtdy1uq31/DASH_96", "dash_url": "https://v.redd.it/9ozrhtdy1uq31/DASHPlaylist.mpd", "duration": 16, "hls_url": "https://v.redd.it/9ozrhtdy1uq31/HLSPlaylist.m3u8", "is_gif": false, "transcoding_status": "completed"}}, "is_reddit_media_domain": true, "is_meta": false, "category": null, "secure_media_embed": {}, "link_flair_text": null, "can_mod_post": false, "num_duplicates": 9, "approved_by": null, "thumbnail": "https://b.thumbs.redditmedia.com/1LMEGlpcGamc412rcLqCch3Do36LaxvUHTzJePkJOdQ.jpg", "edited": false,
Then have 9ozrhtdy1uq31 for later use.
So far I have basically nothing but confusion. I have read other questions asking parts of my needs some using findstr and for /F and Im not sure which to use.
Can anyone help or just find some good resources I can use?

To extract this ID=9ozrhtdy1uq31 from URL in your JSON file, you should try with Regex in vbscript like this code :
#echo off & color 0A
Title Extract ID from URL using Regex in Vbscript
Set "InputFile=%~dp0file.txt"
Call :Extract_ID "%InputFile%" ID
Echo The ID extracted is %ID%
Pause & Exit
::----------------------------------------------------------------------------------------
:Extract_ID <InputFile> <ID to be Set>
(
echo WScript.StdOut.WriteLine Extract_ID(Data^)
echo Function Extract_ID(Data^)
echo Data = WScript.StdIn.ReadAll
echo Set re = New RegExp
echo re.Global = True
echo re.IgnoreCase = True
echo re.Pattern = "https:\/\/[\w\-_]+(\.[\w\-_]+)+\/([\w]*[\w])(/HLSPlaylist.m3u8)"
echo For Each Match in re.Execute(Data^)
echo ID = Match.SubMatches(1^)
echo Next
echo Extract_ID = ID
echo End Function
)>"%tmp%\%~n0.vbs"
for /f "delims=" %%A in ('cscript /nologo "%tmp%\%~n0.vbs" ^< "%~1"') do set "%2=%%A"
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
Exit /B
::----------------------------------------------------------------------------------------
Edit :
Or you can also use Regex in Powershell :
#echo off & color 0A
Title Extract ID from URL using Regex in Powershell
Set "InputFile=%~dp0file.txt"
Set psCmd="&{$content=Get-Content -Path '%InputFile%';[regex]$regex='https:\/\/[\w\-_]+(\.[\w\-_]+)+\/([\w]*[\w])(/HLSPlaylist.m3u8)';$regex.Matches($content).captures.groups[2].value}"
Call :RunPS %psCmd% ID
Echo The ID extracted is %ID%
pause & Exit
::----------------------------------------------------------------------
:RunPS <PassPSCMD> <RetValue>
for /F "usebackq tokens=*" %%i in (`Powershell %1`) do set "%2=%%i"
Goto:eof
:: End of :RunPS function
::----------------------------------------------------------------------

Related

Reading content from 1 .txt file to run commands

I have three scripts:
Script to extract data from my txt file.
Script to copy txt files from a backup folder.
Script to rename the copied txt files.
I was wondering if I can get a little help with merging all three scripts into a single script.
Extract codes.bat:
#echo off
setlocal EnableDelayedExpansion
for /f "tokens=1,2delims=: " %%a in ('findstr "serv fllv" extract.txt') do (
if "%%~a"=="fllv" (
if %%~b geq 1 if %%~b leq 51 (
echo "serv": !serv!
echo "fllv": %%~b
echo/
)
)
set "%%~a=%%~b"
)>> Extract_Details.txt
The content of the txt file to extract from, extract.txt:
{
"serv": 25,
"elcl": 0,
"gacp": false,
"daid": 482,
"gnid": 204,
"caid": 3,
"hzsid": 15,
"yivid": 125,
"khbn": "",
"tlad": 0.0,
"teed": true,
"fllv": 50,
"isra": false
},
{
"serv": 220,
"elcl": 0,
"gacp": false,
"daid": 854,
"gnid": 541,
"caid": 9,
"hzsid": 25,
"yivid": 410,
"khbn": "",
"tlad": 0.0,
"teed": true,
"fllv": 35,
"isra": false
},
Results Extract_Details.txt:
"serv": 25,
"fllv": 50,
"serv": 220,
"fllv": 35,
I was thinking if a script could read Extract_Details.txt, find the first "fllv": 50, and it would look at 50 and run the copy command. Then find "serv": 25, and run a rename command.
I can also have the script rotate them like this if it helps since fllv needs to be copied first, before it is renamed.
"fllv": 50,
"serv": 25,
"fllv": 35,
"serv": 220,
Here are my 2 other scripts:
:Runfllv35
#echo off
copy "0BackupFiles\fllv35.txt" "GetReady\fllv35.txt"
Set /P Fllv=Enter Serv:
ren "GetReady\fllv35.txt" "(%fllv35%).txt"
goto :mainmenu
:Runfllv50
#echo off
copy "0BackupFiles\fllv50.txt" "GetReady\fllv50.txt"
Set /P Fllv=Enter Serv:
ren "GetReady\fllv50.txt" "(%fllv50%).txt"
goto :mainmenu
I have these two scripts repeat fifty times, because the fllv starts from 1 and ends at 50 and I can have over a hundred sets of extracted codes. What I do is, I use the scripts to copy and rename the files for me, and I type in on the CMD data based on Extract_Details.txt
Results after coping and renaming
GetReady
+---- 25.txt
+---- 220.txt

I am trying to filter a text file based on a var in a text file (batch)

For example in my file (loginusers.txt)
if string in my file between { and } is
"MostRecent" "1"
then grab the string "76561199048621574" outside of the brackets and assign to a variable without quotes
and ignore entire other {} if "MostRecent" is "0"
"users"
{
"76561199048621574"
{
"AccountName" "acc1_internalname"
"PersonaName" "acc1_displayname"
"RememberPassword" "1"
"WantsOfflineMode" "0"
"SkipOfflineModeWarning" "0"
"AllowAutoLogin" "1"
"MostRecent" "1"
"Timestamp" "1660477659"
}
"76561198832716662"
{
"AccountName" "acc2_internalname"
"PersonaName" "acc2_displayname"
"RememberPassword" "0"
"WantsOfflineMode" "0"
"SkipOfflineModeWarning" "0"
"AllowAutoLogin" "0"
"MostRecent" "0"
"Timestamp" "1650761551"
}
}
Something like this would probably work for you:
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "vdf=%ProgramFiles(x86)%\Steam\config\loginusers.vdf"
Set "usr="
For /F "Tokens=1,2" %%G In ('%SystemRoot%\System32\findstr.exe /R
"\<\"[0123456789][0123456789]*\"\>" "%vdf%" 2^>NUL') Do (
If Not Defined usr If "%%~H" == "" Set "usr=%%~G"
If Defined usr If /I "%%~G" == "MostRecent" If "%%~H" == "1" (GoTo :Next
) Else Set "usr=")
:Next
If Not Defined usr GoTo :EOF
Echo %%usr%% = %usr%
Pause
However, as this site is not technically a code request and receive service, I will not be explaining any of the above, or modifying it for additional or modified requirements moving forward. Please study the code yourself to determine what it is doing and how. Thank you.
#ECHO Off
SETLOCAL
rem The following settings for the source directory and filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files"
SET "filename1=%sourcedir%\q73352699.txt"
SET "data="
FOR /f "usebackqtokens=1,2" %%b IN ("%filename1%") DO (
IF "%%~c"=="" (
IF %%b=="%%~b" (SET "data=%%~b") ELSE (IF "%%b"=="}" SET "data=")
) ELSE (
IF "%%~b"=="MostRecent" IF "%%~c"=="1" GOTO done
)
)
:done
IF DEFINED data (ECHO Required data: %data%) ELSE ECHO NOT found
GOTO :EOF
Note that if the filename does not contain separators like spaces, then both usebackq and the quotes around %filename1% can be omitted.

How to convert JSON syntax to another one with a cmd.exe batch file (for loop)

I have 10000 tiny tmp/ txt files that look like these:
1.tmp: {"a": "you","data": "1","data2": "2"} <linefeed> {"b":"bo"}
2.tmp: {"a": "you2","data": "1","data2": "2"} <linefeed> {"b":"bo2"}
3.tmp: {"a": "you3","data": "1","data2": "2"} <linefeed> {"b":"bo3"}
How can I read each of them and convert these to another format, one file that has 1 row per file:
{ "a": "you", "b": "bo" },
{ "a": "you2", "b": "bo2" },
{ "a": "you3", "b": "bo3" },
The tricky part might be that each .tmp file has a linefeed?
My code starts
for /L %%i in (0,1,10000) do (call parsesomehow %%i.tmp )
As I understood there were only 2 lines in every tmp file.
You have to read every tmp file. In every cycle you should parse 1-st string. Then - 2-nd. This parce cycle must be the stored procedure
Next step is print parsed values to output file.
#echo off
for %%i in (*.tmp) do call :parse %%i
goto :EOF
:parse
for /f "delims=," %%a in (%1) do set "A=%%a" &goto NXT
:NXT
for /f "delims={" %%a in ('more +1 %1') do set "B=%%a"
echo %A%, %B%>>output.txt

Get values of httpresponse using batch file

For example I have this HTTP Response:
{
"location": {
"lat": 51.0,
"lng": -0.1
},
"accuracy": 1200.4
}
How do I get only the values 51.0 and -0.1? I tried doing it with this:
for /F "tokens=3 delims= " %%a in (foo1.tmp) do (
echo %%a >> url.tmp
)
set /p lat=<url.tmp
more +1 <url.tmp >new.tmp
for /F "tokens=* delims= " %%a in (new.tmp) do (
set var2=%%a
)
I was able to get the first value which was 51.0 but for the second value which as var2, I am getting the 1200.4 value which is supposed to be -0.1. Any help here?
To better explain what my one liner from the comment does:
findstr "lat lng" <foo1.tmp
filters lines containing either lat or lng using default regular expression mode, sample output:
"lat": 51.0,
"lng": -0.1
Instead of using a temporary file, you can directly use curl/wget
To process the output the for /f parses the line with the delimiters :, (colon,comma,space).
Leading delims are ignored, adjacent ones are counted as only one, so
%%A contains "lat" / "lng"
%%B contains 51.0 / "-0.1"
To strip the double quotes from %%A the for variable modifier ~ is used.
In summary the (batch) line:
for /f "tokens=1,2 delims=:, " %%A in ('findstr "lat lng" ^<foo1.tmp') do set "%%~A=%%B"
sets the variables
> set l
lat=51.0
lng=-0.1

Browseforfolder from batch. My hybrid batch/vbscript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Here is a hybrid batch/vbscript I wrote to get a browseforfolder dialog when running a batch file. I've tweaked it as much as my current skill allows and it works pretty well as is but I thought I'd throw it up for critiques or improvements/suggestions.
#Echo off
setlocal
Call :BrowseFolder "Choose Source folder" "C:\scripts\batch\"
Set SourceFolder=%Result%
Call :BrowseFolder "Choose Destination folder" "C:\scripts\"
Set DestinationFolder=%Result%
Echo %SourceFolder%
Echo %DestinationFolder%
cmd /k
endlocal
Goto :EOF
:BrowseFolder
set Result=
set vbs="%temp%\_.vbs"
set cmd="%temp%\_.cmd"
for %%f in (%vbs% %cmd%) do if exist %%f del %%f
for %%g in ("vbs cmd") do if defined %%g set %%g=
>%vbs% echo set WshShell=WScript.CreateObject("WScript.Shell")
>>%vbs% echo set shell=WScript.CreateObject("Shell.Application")
>>%vbs% echo set f=shell.BrowseForFolder(0,%1,0,%2)
>>%vbs% echo if typename(f)="Nothing" Then
>>%vbs% echo wscript.echo "set Result=Dialog Cancelled"
>>%vbs% echo WScript.Quit(1)
>>%vbs% echo end if
>>%vbs% echo set fs=f.Items():set fi=fs.Item()
>>%vbs% echo p=fi.Path:wscript.echo "set Result=" ^& p
cscript //nologo %vbs% > %cmd%
for /f "delims=" %%a in (%cmd%) do %%a
for %%f in (%vbs% %cmd%) do if exist %%f del %%f
for %%g in ("vbs cmd") do if defined %%g set %%g=
goto :eof
Here is a similar example of this functionality in Batch/JScript Hybrid
I have not thoroughly tested this, but wanted to give you an example based on my comment. This method does not require any additional temporary files.
#if (#CodeSection == #Batch) #then
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: The first line in the script is...
:: in Batch, a valid IF command that does nothing.
:: in JScript, a conditional compilation IF statement that is false.
:: So the following section is omitted until the next "[at]end".
:: Note: the "[at]then" is required for Batch to prevent a syntax error.
:: If the task cannot be done in batch, use PowerShell with fallback J/WScript.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Batch Section
#echo off
for /f "delims=" %%A in ('CScript //E:JScript //Nologo "%~f0" FolderBox "Hello Temp" "%Temp%"') do echo %%A
pause
exit /b 0
:: End of Batch
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#end
////////////////////////////////////////////////////////////////////////////////
// JScript Section
try
{
switch(WScript.Arguments.Item(0))
{
case 'FolderBox':
{
var Title = WScript.Arguments.Item(1);
var StartPath = WScript.Arguments.Item(2);
var Shell = WScript.CreateObject('Shell.Application');
var Result = Shell.BrowseForFolder(0, Title, 0, StartPath);
if (Result != null)
{
var Items = Result.Items();
if (Items != null)
{
for (var i = 0; i < Items.Count; i++)
{
WScript.Echo(Items.Item(i).Path);
}
WScript.Quit(0);
}
}
WScript.Quit(1);
}
break;
default:
{
WScript.Echo('Invalid Command: ' + WScript.Arguments.Item(0));
}
break;
}
}
catch(e)
{
WScript.Echo(e);
WScript.Quit(1);
}
WScript.Quit(0);

Resources