w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Replace HTML5 element names from page ignoring the ones wrapped within
 and  tags
You've probably oversimplified the code, as it stands it will only replace the opening tag, which will at least cause the browser to hop into quirks mode. Anyways, this is definitely possible using DOM (though it will throw warnings because of unsupported HTML5 elements, see http://stackoverflow.com/a/6090728/1392379), however your XPath query is wrong, you cannot simply pass an array into it. And even if your query would work, it would only select all the individual text nodes, so there wouldn't be anything to replace. Changing the name of a node is not possible directly, you'll have to replace the node with a new one. Here's an example that uses a static XPath query. It copies the selected nodes attributes and child nodes into a new div node, and then replaces the original node with th

Categories : PHP

JavaScript regex to find special words not wrapped in a tag
Working in my Google Chrome directly on this question, I find following code a promising start in the JavaScript console: Code nodeList = document.querySelectorAll('span'); nodeArray=[]; for (i=0; i < nodeList.length; i++) {nodeArray.push(nodeList[i]);} nodeArray.filter(function(node) {return node.innerText.match(/{variable}/)}); Note how we select actual HTML elements based on the Document Object Model and then look for candidates based on their text content. Alternatively one could use .innerHTML, or actually manipulate document content via assignment to these properties. Result [ <span class=​"str">​ "/span> wrapped without the attribute, but this one <span data-placeholder="val">{variable}</" </span>​ , <span class=​"pln">​{variable}​

Categories : Javascript

Find and replace duplicates in Array, but replace each nth instance with a different string
EDIT Counter and than sorting is simpler: L = ['champ', 'king', 'king', 'mak', 'mak', 'mak'] counts = Counter(L) res = [] for word in sorted(counts.keys()): if counts[word] == 1: res.append(word) else: res.extend(['{}{}'.format(word, index) for index in range(1, counts[word] + 1)]) So this ['champ', 'mak', 'king', 'king', 'mak', 'mak'] also gives: ['champ', 'king1', 'king2', 'mak1', 'mak2', 'mak3']

Categories : Python

How to find, filter and copy directory and contents to a location dictated by part of find result ) in Powershell
This should work: $specialdirectory = "xyz" $Destination = "zyx" $1 = "\fileserverprofiles" | Get-ChildItem $User = $1.Name | where {$_ -Match "User"} $User | foreach { $check = test-path -pathtype Any "\fileserverprofiles$_appdata$Specialdirectory" If ($check -eq $true) {Copy-Item \fileserverprofiles$_appdata$specialdirectory -Destination C:$Destination -Recurse} }

Categories : File

Powershell search and replace
Your example shows you creating the text file by recursing through a folder the desktop, you don't need a text file to loop through, you could just use that, but lets say you do generate the text file of short name like you state. $short_file_names = Get-Content C:PathTo500_Short_File_Names_No_Extensions.txt Now you can loop through that array in two ways: Using the foreach keyword: foreach ($file_name in $short_file_names) { # ... } Or using the ForEach-Object cmdlet: $short_file_names | ForEach-Object { # ... } The big difference is that the current item will be a named variable $file_name in the first and a non-named built-in $_ variable in the second. Let's say you use the first. You need to see if $file_name is in the second file and if so record that you found it.

Categories : Search

Powershell - using variables in replace
Unlike the Replace method which takes strings, the replace operator takes a regular expression pattern. $SourcePath needs to be escaped as it contains backslashes which are special regex characters. $sourceFileRelativePath = $sourceFullPath -replace [regex]::escape($SourcePath) $destFullFilePath = Join-Path $folder $sourceFileRelativePath

Categories : Powershell

In NotePad++ find and replace, how would I use what I found in my replace?
Enclose it in parentheses in your find. request.POST[("[a-z A-Z _]*")] Then use 1 in your replace. That will return what was captured by the first set of parentheses. (Use 2, 3, etc. if you have multiple capturing groups.

Categories : Regex

Sharepoint & PowerShell - StringBuilder.Replace
Ok, sod's law that I find a solution shortly after posting on here..! The following works for me. I'd experimented with 'r and 'n with no luck, but by doing both of them together with NewLine, all line breaks are now being stripped out: $log = "C:mylogfile.csv" $newline = [System.Environment]::NewLine $charsToStrip = "`r","`n", $newline $sb2 = New-Object System.Text.StringBuilder $sb2.Append("Text fields") foreach ($char in $charsToStrip) { $sb2.Replace($char,".") } $sb2.ToString() | Out-File $log -Append

Categories : Powershell

Powershell replace exact string
The reason why this happened is because you have used pattern WEEK. The dot was a problem: in a regular expression world, the dot means "any character". That's why it was replacing both WEEK_ and WEEK.. When you have added backslash, then the dot was escaped ie. it lost it's special meaning. Thus making it work.

Categories : Regex

replace tag in *dtsConfig file from powershell
Your code should be like following: ls C: empSTA*.dtsConfig | foreach { $file = $_.FullName; $xml = [xml](Get-Content $file) $todayStr = [datetime]::Today.ToString('_MMddyyy') @($xml.SelectNodes('//ConfiguredValue')) | %{ $_.'#text'=($_.'#text' -replace '_d+',$todayStr) } $xml.Save($file) }

Categories : Powershell

What causes the error that says "Could not find the Service Class" for a service wrapped by WinRun4j
I believe you are using two incompatible parameters in your service.ini. You must introduce either service.class or main.class, but not both. If you want your .exe to be executed always as a service, you must use service.class and register it in the Windows Service Manager, like so: executable.exe --WinRun4J:RegisterService If you want it to be a normal application, you must use main.class and call it normally. If you want to execute it in both ways, you have to fall back to some roundabout like the one here. CopyPasting from the link: I have the same requirement, for what will be around 10 or so services. Each must also be available to support people for command line execution, passing optional parameters for a "single run" mode of operation. I have simply created a p

Categories : Java

Powershell: Force immediate evaluation of backreference during replace
1st, missing the point, answer replaced... When concatenate '$1' and '6Q' (before being passed to the regex engine) you get $16Q and there is no 16th capture to replace. To avoid this, use named groups in the match ((?<name>)) and ${name} in the replacement string. See the documentation, and note: If number does not specify a valid capturing group defined in the regular expression pattern, $number is interpreted as a literal character sequence that is used to replace each match.

Categories : Powershell

String replace file content with PowerShell
Use (V3 version): (Get-Content c: emp est.txt).replace('[MYID]', 'MyValue') | Set-Content c: emp est.txt Or for V2: (Get-Content c: emp est.txt) -replace '[MYID]', 'MyValue' | Set-Content c: emp est.txt

Categories : Powershell

Use Powershell to replace characters within a specific string
Try this regex: "(?<!?xml.*)(?<=`".*?)`"(?=.*?`")" In your code it would be: (Get-Content C: estcommunication.xml) | Foreach-Object {$_ -replace "&", "+" ` -replace "£", "GBP" ` -replace "'", "" ` -replace "–", " " ` -replace "(?<!?xml.*)(?<=`".*?)`"(?=.*?`")", ""} | Set-Content C: estcommunication.xml This will take any " that has a " in-front of and behind it (except a line that has ?xml in it) and replace it with nothing. Edit to include breakdown of regex; (?<!?xml.*)(?<=`".*?)`"(?=.*?`") 1. (?<!?xml.*)----> Excludes any line that has "?xml" before the first quote 2. (?<=`".*?)------> Lookbehind searching for a quotation mark. The ` is to escape the quotation mark, which is needed for powershell 3. `"--------------

Categories : Xml

Powershell - Replace XML content with an environment variable
You need to put the environment variable inside double quotes so it can be expanded. Single quoted strings are not expandable: ... -replace '<Password>(.*?)</Password>', "<Password>$env:HIS_PWD</Password>"

Categories : Xml

How to find with lookahead in Visual studio 2012 Regex Find and Replace
You need to add a (?s), which enables multiline matching, and also escape the period in using Example.Foo. The regex should be something along the lines of: (?s)using Example.Foo;(?=.*BaseClass<SomeClass>)

Categories : Regex

Mongo find - replace ObjectId with attribute of object when find
Actually you don't have to use ObjectId as a data type for _id field. You can use set _id explicitly using any data type for example string: > db.users.insert({_id: 'johndoe', age: 21}) > db.users.insert({_id: 'janedoe', age: 27}) > db.users.find({_id: 'janedoe'}) { "_id" : "janedoe", "age" : 27 } or integer db.items.insert({_id: 1, name: 'someitem'}) > db.items.find() { "_id" : 1, "name" : "someitem" } as long as you can guarantee it has unique value: db.users.insert({_id: 'janedoe', age: 26}) E11000 duplicate key error index: foo.users.$_id_ dup key: { : "janedoe" } For the other hand ObjectID is meaningful, and can be used to obtain document creation time: http://docs.mongodb.org/manual/reference/object-id/

Categories : Mongodb

Powershell Regular Expressions getting values out of a -replace match
Split the string and cast valid values to integers. function doubleIt($digits = "1 2 3 4 5") { #[string](-split $digits -as [int[]] | ForEach-Object {$_*2}) [string](-split $digits | where {$_ -as [int]} | foreach {2*$_} ) }

Categories : Regex

PowerShell Get-Content and replace object in a specific line
Check if a line is starting with a 'Static Text ' followed by a sequence of word characters and return your string in case there a match: Get-Content $OptionsFile | foreach { if($_ -match '^Static Texts+(w+s)+') { 'Static Text MachineX MachineY' } else { $_ } }

Categories : Regex

Find and replace that can find a string that has an unknown number
Assuming that the elements you want to remove from your XML are the only ones with the attribute/value Name="FitToLargest" then you could use a LINQ to XML query to get those elements by attribute name and then remove them. For example: //this will be a path to your XML file or a string containing the XML //I've used 'tbLoad.Text' as I don't know where you're getting the XML from XDocument xml = XDocument.Load(tbLoad.Text); xml.Descendants().Elements("Hmi.Screen.Property") .Where(e => e.Attribute("Name").Value == "FitToLargest").Remove(); xml.Save("file path here..."); This will remove all Hmi.Screen.Property elements that have FitToLargest as their Name attribute.

Categories : C#

Extend PowerShell to search/replace and perform on all files in directory?
Try this: import-csv .chapters.csv | ConvertTo-Json -Compress | Foreach {$_ -creplace 'NULL','null'} | Out-File .chapters.json The -replace operators can be used to replace text within a string.

Categories : Powershell

How can I use Find and Replace with REGEX to find a parameter and replace it with the parameter
In notepad++ you can use this: Find what: CREATE TABLE (.*?)( Replace with: IF OBJECT_ID(N'SQL_DB..1', N'U') IS NOT NULL DROP TABLE 1; GO CREATE TABLE 1( Move the cursor to the beginning of the file and hit Replace All. This will turn your sample input into your sample output. What did I do? I escaped the parenthesis in the Replace With expression. Also included the ( in the find what (so it is more accurate) and at the end of the Replace With.

Categories : SQL

How to find MAX RAM in powershell
For installed RAM you want: Get-WmiObject Win32_PhysicalMemory | Where {$_.MemoryType -ge 20} | Measure Capacity -sum Look at this MSDN page for more info on MemoryType. For the MAX amount of RAM the system will handle, I think this is supposed to get you that. However, I don't think that means the OS or the motherboard would necessarily handle that much memory. I see nothing on the Win32_MotherboardDevice that shows max RAM. Get-WmiObject Win32_PhysicalMemoryArray | Where {$_.Use -eq 3} | Foreach {($_.MaxCapacity*1KB)/1GB} Here's the MSDN page for Win32_PhysicalMemoryArray.

Categories : Powershell

How to find information in powershell?
I am not familiar with powershell scripting but found this, maybe some reference to use: http://technet.microsoft.com/eng-us/scriptcenter/powershell%28en-us%29.aspx http://technet.microsoft.com/en-us/library/hh857339.aspx#BKMK_wps4 On the first link are PowerShell Scripting Webcasts to find and more. Scheduling Jobs with the Windows PowerShell API: http://msdn.microsoft.com/en-us/library/windows/desktop/jj150476%28v=vs.85%29.aspx Guide to getting started with Windows PowerShell: http://technet.microsoft.com/library/ee221100.aspx About Windows PowerShell, following help topics: get-command : Gets information about cmdlets from the cmdlet code. get-member : Gets the properties and methods of an object. where-object : Filters object properties. about_object : Exp

Categories : Powershell

Powershell/PoshGit - 'Could not find ssh-agent'
You just need to reverse those two lines in your Microsoft.PowerShell_profile.ps1 so that the PATH environment variable is updated to include the Git bin path before you include the posh-git profile. On my PC this is what it looks like: I start PowerShell and get the warning message: WARNING: Could not find ssh-agent I locate and edit the PowerShell profile using $profile: C:Usersglombard> notepad $profile Update the $env:path to include the path to git before loading the posh-git example profile: $env:path += ";${env:ProgramFiles(x86)}Gitin" # Load posh-git example profile . 'C: oolsposhgitdahlbyk-posh-git-22f4e77profile.example.ps1'

Categories : GIT

How to find if a list of computers on are a domain using Powershell?
You can use the code with -Computername parameter and provide explicit credentials in case the remote computer administrator credentials are different from what you are using. $cred = Get-Credential $servers = Get-Content C:scriptsServers.txt Foreach ($server in $servers) { if ((gwmi win32_computersystem -computername $server -Credential $cred).partofdomain -eq $true) { #Do something Here } else { #Do something Here }

Categories : List

How do I find the Collection Membership Information with PowerShell
Rather than connecting to each computer and extracting the information (slow) get it from the straight from the database.... [CmdletBinding()] param ( [string] $hosts = "", [string] $sccmsrv = "", [Parameter(Mandatory=$False,Position=3)] [string] $path = "" ) $usage = "USAGE: List-AdvertCollMembershipSCCM.ps1 -sccmsrv SCCMSERVER -hosts 'host1 host2 host3' -path 'c: empOutfile.csv'" if ($host -and $sccmsrv){ Write-Host "" Write-Host -ForegroundColor Yellow "SCCM Server: $sccmsrv" Write-Host -ForegroundColor Yellow "Looking at hosts: $hosts" #### Function for executing a SQL query with integrated authentication function execSQLQuery ([string]$fSQLServer, [string]$db, [string]$query){ $objConnection = New-Object System.Data.SqlCli

Categories : Powershell

How do I find out if a class and a method exist in .NET dll, from powershell?
I'm not sure I fully understand your question but if you already have the assembly, GetTypes will list all types (public and private) contained in the assembly. $assembly = [System.Reflection.Assembly]::LoadWithPartialName("System.Xml") $assembly.GetTypes() | where-object { $_.name -eq "XmlNode" } You can then call GetMembers or GetMethods to list the members/methods for a given type. See http://msdn.microsoft.com/en-us/library/System.Type_methods.aspx for the detailed API.

Categories : Dotnet

Powershell : Find the first free computer name in Active Directory
Try something like this: Import-Module ActiveDirectory $computers = Get-ADComputer * | % { $_.Name -replace 'PC' } $i = 1 while ( $computers -contains ("{0:d2}" -f $i) ) { $i++ } $computername = "PC{0:d2}" -f $i echo $computername

Categories : Powershell

Powershell script can't find module when run via -File param
I'm dumb :P There is a dropdown in TeamCity where you can select the runmode of x86 or x64. It was set to x86. I changed it to x64. Now it executes under the correct version. Still curious why the modules wouldn't load in x86 though... Also, it's weird that SysWOW64 correlates to x86 and System32 correlates to x64

Categories : Powershell

Find unique/distinct files in windows powershell.
cd c:Folder ls | ? { -not $_.PSIsContainer -and $_.BaseName -cmatch 'Esd{2}' } | % { $folder = $matches[0] new-item -ItemType Directory -Path . -Name $folder -ErrorAction SilentlyContinue move-item $_.Name $folder } Idk if this helps, but I suggest more research. If you were talking about just doing ls | ? {$_.Name -cmatch "Esd{2}"} | select unique That might not be very useful

Categories : Sorting

Powershell to find and rename duplicate values in list items
This should do it: #Add-PSSnapin microsoft.sharepoint.powershell $web = Get-SPWeb -Identity "siteURL/" $list = $web.Lists["Products"] $AllDuplicateNames = $list.Items.GetDataTable() | Group-Object SAPMaterial | ?{$_.count -gt 1} | %{$_.Name} foreach($duplicate in $AllDuplicateNames) { $dupsaps = $list.Items | ?{$_["SAPMaterial"] -eq $duplicate} $count = 1 foreach($sap in $dupsaps) { $sap[“SAPMaterial”] = $duplicate + "_" + $count $sap.Update() $count++ } } Edit: just found a bug should work now but don't have a sharepoint site to test let me know if it works. You should probably backup before running this to be sure.

Categories : Powershell

parse logfile for keyword using powershell and execute command on find
This should work: $logfile = "..." Get-Content $logfile | ? { $_ -match "keyword" } | % { command break } For ignoring matches from previous runs you need to store some signifying criteria of the current match (e.g. a timestamp) and include that in your filter. Can't help you with that without knowing what your logfile looks like, though. Edit: If you have a timestamp in each line, you can store the timestamp from the previous run in a file and use that for comparison. $logfile = "..." $lastfile = "C:path olastmatch.txt" if (Test-Path -LiteralPath ) { $last = Get-Date (Get-Content $lastfile) } else { $last = Get-Date "1970-01-01 00:00:00" # reference date } $pattern = '^l(d{4}-d{2}-d{2} d{2}:d{2}:d{2]).*keyword' Get-Content $logfile | ? { $_ -match $pattern -and (Get-Dat

Categories : Powershell

Find and replace one CSV from another CSV
Not sure if I understand your question correctly, but you can scan your replacement file noting what needs to be replaced with what value. And then iterate over list file and swap the replacement value with newer value. Something like this: awk 'NR==FNR{a[$1]=$2;next} $2 in a{print $1,a[$2]}' replacement.txt list.txt Test: $ cat list.txt Name id John 1 Amber a $ cat replacement.txt id.1 id.2 1 2 a b $ awk 'NR==FNR{a[$1]=$2;next} $2 in a{print $1,a[$2]}' replacement.txt list.txt John 2 Amber b

Categories : Search

Find and replace @n with a something else
The @n refers to an array, which is empty. When an empty array is interpolated, the result is the empty string. Therefore, your command would seem to delete all &00 occurrences. Escaping the @ should help here: perl -i -wpe's/&00/@n/g' *.wld (flags that don't take an argument can be stacked)

Categories : Regex

find and replace with regex C#
You know that in |d| the | means or? Try escaping it! @"|d|" Your regular expression was equivalent to "" (empty string). This because you must see it as (match of empty string) or (match of letter d) or (match of empty string) always matched from left to right, stop at the first positive match. As we will see, just the first condition (match of empty string) is positive everywhere, so it won't ever go to the other matches. Now, the regex parser will try to match your regex at the start of the string. It is at "/" (first character): does it match? is "" part of "/"? Yes (at least in the "mind" of the regex parser). Now the funny thing is that Regex.Replace will replace the matched part of the string with 17... But funnily the matched part of "/" is "", so it will replace an imagina

Categories : C#

Using Regex to Find and Replace
Your example code has an extra '(' that does not belong. This is what the line should be: new_line = re.sub(r'd{4}+d{2}', FeetFramesToTimecode(found.group()), line) This produced output for me like you want.

Categories : Python

RegEx find and replace
Try using: ^(d+,$ For find and nothing for the replace? EDIT: As per update, try using this: (?<=()d+,s* And replace with nothing.

Categories : Regex

Eclipse - Find and replace in xml
In the Find/Replace dialog, under Options, check Regular expressions, and replace City Code=".*?" with an empty string. You can read more about regular expressions here.

Categories : Xml

vba conditional find & replace
The only required arguments for Replace are What and Replacement, which you have supplied. I do not receive an error message about this but I do with this line: If wsS.Range(col1 & a) = wsN.Range("AB2:ab600") Then because you are trying to compare a single value with a Range. (I'm assuming that wsS and wsN are set correctly to worksheets.) This is the likely cause of any errrors. But as your error message is different I am suspicious that you are not posting your actual code, or enough of it for us to replicate your problem.

Categories : Vba



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.