I have the following script, but no success executing it without errors. I want to put a variable into a URL and ping that URL.
#include <Excel.au3>
$sFilePath1 = "D:\Desktop\1.xlsx"
$oExcel = _ExcelBookOpen($sFilePath1, 0)
For $i = 1 To 2 ; Loop
Local $username = _ExcelReadcell($oExcel, $i, 1) ;Reading created Excel
Local $iPing = Ping("http://blogsearch.google.co.in/ping?url="$username"&btnG=Submit+Blog&hl=en", 2500)
If $iPing Then ; If a value greater than 0 was returned then display the following message.
MsgBox(0, "STATUS", "Ping Successful", 1)
Else
MsgBox(0, "STATUS", "ERROR", 1)
EndIf
Next
As Teifun2 showed, you just need to write your text between quotes or dual quotes, and then put "&" between the last quote ad the variable, this way :
"I am writing this between double quotes at line # " & $i_Nbr & ' with simple quotes!'
Like Xenobiologist already said in comments to the question, this should just work fine:
#include <Excel.au3>
$sFilePath1 = "D:\Desktop\1.xlsx"
$oExcel = _ExcelBookOpen($sFilePath1, 0)
For $i = 1 To 2 ;Loop
Local $username = _ExcelReadcell($oExcel, $i, 1) ;Reading created Excel
Local $iPing = Ping("http://blogsearch.google.co.in/ping?url="&$username&"&btnG=Submit+Blog&hl=en", 2500)
If $iPing Then ; If a value greater than 0 was returned then display the following message.
MsgBox(0, "STATUS", "Ping Successful" ,1)
Else
MsgBox(0, "STATUS", "ERROR" ,1)
EndIf
Next
You can concatenate the variable to the string
$id = 21622809
MsgBox(0, '', "http://example.com/user/" & $id & "/blah_blah_blah")
or enable the ExpandVarStrings option and use the variable
$id = 21622809
Opt("ExpandVarStrings", 1)
MsgBox(0, "", "http://example.com/user/$id$/blah_blah_blah")
Related
I wanted to assign variable name separated by comma based on user input using function.
I will get the user input using below script and it will call function for variable assignment
while [ "$ans" != "q" ]
do
clear
echo "Choose your subject"
echo "Press q once done"
echo " 1.Science"
echo " 2.Maths"
echo " 3.English"
...
read ans
case $ans in
1) clear
Science;;
2) clear
Maths;;
3) clear
English;;
....
esac
done
clear
subjects=""
Science()
{
subjects+="$subjects Science"
}
Maths()
{
subjects+="$subjects Maths"
}
English()
{
subjects+="$subjects English"
}
At the end I wanted to have variable subjects to have option choose by the user:
Etc:
Science,Maths
Maths,English
Science,English
English
In bash, the function definition must be placed before any calls to the function.
The line subjects="" must be placed before the while loop. Otherwise its value will get lost (will be set to empty string) on exit from the loop.
The += operator causes double concatenation in the line subjects+="$subjects Science", since the right hand side contains already the expansion of the subjects variable. Either subjects="$subjects Science", or subjects+=" Science" must have been used (the same is also true for other lines in which the += operator is used). Besides, since a comma separated list is desired, a , character must be used while concatenating strings instead of space character. For example: subjects="$subjects,Science"
So a corrected script could be like this:
#!/bin/bash
subjects=""
Science() {
subjects="$subjects,Science"
}
Maths() {
subjects="$subjects,Maths"
}
English() {
subjects="$subjects,English"
}
while [ "$ans" != "q" ]; do
clear
echo "Choose your subject"
echo "Press q once done"
echo " 1.Science"
echo " 2.Maths"
echo " 3.English"
read -r ans
case $ans in
1) Science;;
2) Maths;;
3) English;;
esac
done
subjects=${subjects:1} # to remove the leading ',' character
echo "Your selections are $subjects"
Note: I wouldn't normally use a function just to append a simple string to a variable.
So I am creating a program that separates numbers and letters into 2 different variables so it turns "word1234" into a variable containing "word" and a variable containing "1234", what I did was make a program that runs through a variable "info" letter by letter. "Is it a number?" "No", "Is It a letter?" "Yes". When the variable "toggle" was still on the value 0, it would carry on appending the letters to the "weatherd" variable and else append it to the "temperat" variable.
Note: I know my variable and label names are bad, I come up with them in about half a second :)
So it checks if it is a number, if it is the "toggle" variable changes to a 1 and it starts putting the rest of the text into a new variable ("temperat"). I was wondering, once it hits the numbers it gives me an error and crashes, why? Or is there a simpler way than what I'm doing?
Sorry for the massive post, I added some pauses and stuff for debugging, code here:
REM PREPARE FOR A MASSIVE AMOUNT OF CODE, all this stuff just gets the current weather, ignore it
#echo off
set "wherestay=%cd%"
cd /d C:
cd\
cd "C:/Users/%USERNAME%/Downloads"
del weather.txt
start chrome.exe teamhaxor.netau.net/getWeather.php
set times=0
:loading
set /a times=%times% + 1
if %times% == 2000 goto failed
if not exist weather.txt goto loading
cd /d C:
cd\
cd "C:/Users/%USERNAME%/Downloads"
< weather.txt (
set /p info=
)
REM PROBLEM STARTS HERE
setlocal enabledelayedexpansion
#echo on
set tempery=0
set "weatherd="
set "temperat="
set toggle=0
:loopy
set "char=!info:~%tempery%, 1!"
if "%char%" EQU "0" set toggle=1
if "%char%" EQU "1" set toggle=1
if "%char%" EQU "2" set toggle=1
if "%char%" EQU "3" set toggle=1
if "%char%" EQU "4" set toggle=1
if "%char%" EQU "5" set toggle=1
if "%char%" EQU "6" set toggle=1
if "%char%" EQU "7" set toggle=1
if "%char%" EQU "8" set toggle=1
if "%char%" EQU "9" set toggle=1
pause
if %toggle% EQU 0 (set weatherd=%weatherd%%char%) ELSE (set temperat=%temperat%%char%)
pause
set /a tempery=%tempery% + 1
pause
if %tempery% EQU 15 (goto out) ELSE (goto loopy)
:out
echo %weatherd%
echo %temperat%
setlocal disabledelayedexpansion
REM PROBLEM STOPS HERE
goto afterafterlol
:failed
set weatherd=Failed
set temperat=Failed
:afterafterlol
cd /d C:
cd\
cd %wherestay%
echo %weatherd%
echo %temperat%
pause >Nul
To answer your question directly, there's an easier way to split your value so that you end up with alpha in one variable and numeric in another.
Treat numbers as delimiters, thereby removing them without having to know specifically which numbers will occur. This will leave you with only the alphabetic portion of the value.
Remove the alphabetic portion from the whole, leaving you with the numeric porition.
#echo off & setlocal
set "var=Thunderstorms87"
for /f "delims=0123456789" %%I in ("%var%") do set "condition=%%~I"
call set "temperature=%%var:%condition%=%%"
echo %condition%
echo %temperature%
In a broader sense, your project seems like a very cumbersome way to scrape not a lot of useful data. It would be better to query a weather service that offers an API with a structured response that doesn't require splitting strings or other flat text hacks.
Here's an example script that uses Weather Underground's API, retrieving and parsing its JSON response. You'll need to create an account and sign up for a free API key, but you get so much more data and it's so much easier to parse. And there's no need to spawn a Chrome window to fetch your data this way.
#if (#CodeSection == #Batch) #then
#echo off & setlocal
rem // weather.bat
rem // https://stackoverflow.com/a/44015647/1683264
rem // go to https://www.wunderground.com/weather/api/ for an API key
set "APIkey=pasteyourAPIkeyhere"
if "%~1"=="" ( set "location=autoip" ) else set "location=%~1"
cscript /nologo /e:JScript "%~f0" "%APIkey%" "%location%"
rem // end main runtime
goto :EOF
#end // end batch / begin JScript chimera
var x = WSH.CreateObject("Microsoft.XMLHTTP"),
htmlfile = WSH.CreateObject('htmlfile'),
APIkey = WSH.Arguments(0),
loc = WSH.Arguments(1),
URL = 'http://api.wunderground.com/api/' + APIkey + '/conditions/q/' + loc + '.json',
JSON = obj = {}, pad = ' ';
htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
htmlfile.close(JSON = htmlfile.parentWindow.JSON);
x.open("GET", URL, true);
x.setRequestHeader('User-Agent','XMLHTTP/1.0');
x.send('');
while (x.readyState!=4) {WSH.Sleep(50)};
response = JSON.parse(x.responseText).current_observation;
obj = {
"station": response.observation_location.full,
"timestamp": response.observation_time,
"conditions": response.weather,
"temperature": response.temperature_string,
"humidity": response.relative_humidity,
"wind": response.wind_string,
"heat index": response.heat_index_string,
"wind chill": response.windchill_string,
"forecast URL": response.forecast_url
};
for (var i in obj) while (i.length > pad.length) pad += ' '
for (var i in obj) {
var key = (i + pad).substring(0, pad.length);
WSH.Echo(key + ' : ' + obj[i]);
}
Output looks something like this:
You can use something like:
WSH.Echo(x.responseText);
... to view the raw JSON and see all the other data included in the feed. You can also modify the URL and replace conditions with forecast, hourly, and a bunch of other options (as well as replacing current_observation and the response object properties as appropriate).
I have a shell script that is doing something.I want to print the Unknown string where there is blank space in the output.
I want to do check if (f[1] == "") or (f[2] == "") or (f[3] == ""), it should be replaced by a unknown string and should be written in a single file
if(f[1] == "") printf(fmt, id, f[1], f[2], f[3]) > file
where f[1],f[2],f[3] if empty should be replaced by unknown string
where f[1] is the first index, fmt is the format specifier I have defined in the code.How to replace these empty spaces with a string in Linux.
Any lead is appreciated.
Thanks
Use the conditional operator:
ec2-describe-instances | awk -F'\t' -v of="$out" -v mof="$file" '
function pr() { # Print accumulated data
if(id != "") { # Skip if we do not have any unprinted data.
printf(fmt, id, f[1], f[2], f[3]) > of
if (f[1] == "" || f[2] == "" || f[3] == "") {
printf(fmt, id, f[1]==""?"Unknown":f[1], f[2]==""?"Unknown":f[2], f[3]==""?"Unknown":f[3]) > mof
}
}
# Clear accumulated data.
id = f[1] = f[2] = f[3] = ""
}
BEGIN { # Set the printf() format string for the header and the data lines.
fmt = "%-20s %-40s %-33s %s\n"
# Print the header
headerText="Instance Details"
headerMaxLen=100
padding=(length(headerText) - headerMaxLen) / 2
printf("%" padding "s" "%s" "%" padding "s" "\n\n\n", "", headerText, "") > of
printf(fmt, "Instance id", "Name", "Owner", "Cost.centre") > of
printf("%" padding "s" "%s" "%" padding "s" "\n\n\n", "", headerText, "") > mof
printf(fmt, "Instance id", "Name", "Owner", "Cost.centre") > mof
}
$1 == "TAG" {
# Save the Instance ID.
id = $3
if($4 ~ /[Nn]ame/) fs = 1 # Name found
else if($4 ~ /[Oo]wner/) fs = 2 # Owner found
else if($4 ~ /[Cc]ost.[Cc]ent[er][er]/) fs = 3 # Cost center found
else next # Ignore other TAGs
f[fs] = $5 # Save data for this field.
}
$1 == "RESERVATION" {
# First line of new entry found; print results from previous entry.
pr()
}
END { # EOF found, print results from last entry.
pr()
}'
I have a String like this:
Info1|Info2
I want this String to be splitted by | and a it should return the second Info and the first one.
So I want one msgbox displaying Info1 and another one displaying Info2.
How can I do this?
I already tried
StringSplit
But without any success...
Try this :
#Region ;************ Includes ************
#Include <Array.au3>
#EndRegion ;************ Includes ************
$str = 'Info1|Info2'
$array = StringSplit($str, '|', 2)
For $i = 0 To UBound($array) - 1
MsgBox(64, $i, $array[$i], 1)
Next
_ArrayDisplay($array) ; example
#include <File.au3>
#include <Zip.au3>
#include <Array.au3>
; bad file extensions
Local $extData = "ade|adp|app|asa|ashx|asp|bas|bat|cdx|cer|chm|class|cmd|com|cpl|crt|csh|der|exe|fxp|gadget|hlp|hta|htr|htw|ida|idc|idq|ins|isp|its|jse|ksh|lnk|mad|maf|mag|mam|maq|mar|mas|mat|mau|mav|maw|mda|mdb|mde|mdt|mdw|mdz|msc|msh|msh1|msh1xml|msh2|msh2xml|mshxml|msi|msp|mst|ops|pcd|pif|prf|prg|printer|pst|reg|rem|scf|scr|sct|shb|shs|shtm|shtml|soap|stm|url|vb|vbe|vbs|ws|wsc|wsf|wsh"
Local $extensions = StringSplit($extData, "|")
; What is the root directory?
$rootDirectory = InputBox("Root Directory", "Please enter the root directory...")
archiveDir($rootDirectory)
Func archiveDir($dir)
$goDirs = True
$goFiles = True
; Get all the files under the current dir
$allOfDir = _FileListToArray($dir)
$tmax = UBound($allOfDir)
For $t = 0 To $tmax - 1
Next
Local $countDirs = 0
Local $countFiles = 0
$imax = UBound($allOfDir)
For $i = 0 To $imax - 1
If StringInStr(FileGetAttrib($dir & "\" & $allOfDir[$i]), "D") Then
$countDirs = $countDirs + 1
ElseIf StringInStr(($allOfDir[$i]), ".") Then
$countFiles = $countFiles + 1
EndIf
Next
If ($countDirs > 0) Then
Local $allDirs[$countDirs]
$goDirs = True
Else
$goDirs = False
EndIf
If ($countFiles > 0) Then
Local $allFiles[$countFiles]
$goFiles = True
Else
$goFiles = False
EndIf
$dirCount = 0
$fileCount = 0
For $i = 0 To $imax - 1
If (StringInStr(FileGetAttrib($dir & "\" & $allOfDir[$i]), "D")) And ($goDirs == True) Then
$allDirs[$dirCount] = $allOfDir[$i]
$dirCount = $dirCount + 1
ElseIf (StringInStr(($allOfDir[$i]), ".")) And ($goFiles == True) Then
$allFiles[$fileCount] = $allOfDir[$i]
$fileCount = $fileCount + 1
EndIf
Next
; Zip them if need be in current spot using 'ext_zip.zip' as file name, loop through each file ext.
If ($goFiles == True) Then
$fmax = UBound($allFiles)
For $f = 0 To $fmax - 1
$currentExt = getExt($allFiles[$f])
$position = _ArraySearch($extensions, $currentExt)
If #error Then
MsgBox(0, "Not Found", "Not Found")
Else
$zip = _Zip_Create($dir & "\" & $currentExt & "_zip.zip")
_Zip_AddFile($zip, $dir & "\" & $allFiles[$f])
EndIf
Next
EndIf
; Get all dirs under current DirCopy
; For each dir, recursive call from step 2
If ($goDirs == True) Then
$dmax = UBound($allDirs)
$rootDirectory = $rootDirectory & "\"
For $d = 0 To $dmax - 1
archiveDir($rootDirectory & $allDirs[$d])
Next
EndIf
EndFunc
Func getExt($filename)
$pos = StringInStr($filename, ".")
$retval = StringTrimLeft($filename, $pos - 1)
Return $retval
EndFunc
I have a list of file extensions. This script should go through a directory (and subdirectories), zip up (separate zip files for each extension) all files with those extensions.
Why does it not create zip files?
In the function StringTrimLeft("string", count), count is the number of characters to trim.
$filename = "filename.zip"
$pos = StringInStr($filename, ".") ; $pos will be equal to 9
so...
$retval = StringTrimLeft($filename, $pos + 1); this will remove 10 characters = ip
Two suggestions:
Add MsgBox(0, "Zip", "Got here") inside your If ($currentExt == $extensions[$e]) Then. You should see that you are never getting there.
Related to the above, your getExt function is not returning the correct value for the extension of the file.
UPDATE
You went a little too far with your edit to getExt.
Try this:
Func getExt($filename)
$pos = StringInStr($filename, ".")
$retval = StringTrimLeft($filename, $pos)
Return $retval
EndFunc
UPDATE 2
Regarding your problem where it doesn't process folders beyond the 2nd level, your issue is you are using $rootDirectory in your recursive call where you need to use $dir.
Change the last part of your archiveDir function to this:
; For each dir, recursive call from step 2
If ($goDirs == True) Then
$dmax = UBound($allDirs)
$dir = $dir & "\"
For $d = 0 to $dmax - 1
archiveDir($dir & $allDirs[$d])
Next
EndIf
I tried running your code as is, and sure enough, it failed. I then put a
MsgBox(0, "error", #error & " " & $currentExt)
in the "If #error" block to see if I could find out why it was failing. The result was the #error came back as 6. Looking into the documentation, it says that an error code of 6 means that the value searched for was not found in the array. And then the $currentExt told me it's value was set to ".asp".
The reason it could not be found was because there are no periods in the extension names in the array. If you look closer at the getExt() function, before you were adding 1 to the $position value... and now you are subtracting 1 from the value... Here's an illustration of how StringTrimLeft() works...
$filename = "filename.txt"
$pos = StringInStr($filename, ".") ; $pos will be equal to 9
$retval = StringTrimLeft($filename, $pos + 1); this will remove 10 characters = xt, that's too much.
$retval = StringTrimLeft($filename, $pos - 1); this will remove 8 characters = .txt, that's not enough.
$retval = StringTrimLeft($filename, $pos); this will remove 9 characters = txt, that's juuuuuuust right!
So the solution is to either add "." in front of all of the extensions in your array, or change your getExt() function:
Func getExt($filename)
$pos = StringInStr($filename, ".")
$retval = StringTrimLeft($filename, $pos)
Return $retval
EndFunc
There is one more option you could look into, and that is using the _PathSplit() function found in File.au3, but since your script is so close to working at this point, I wouldn't worry about it, but maybe in the future you could use it instead.
And one last note... After I changed getExt() to drop the ".", your script ran great.