Issue finding and replacing regex in Powershell - string

I have an ini file that looks like this:
[list_text]
text_002=L-Win+3=Regards\nThomas
I try to find and replace the "\nThomas" with a different name:
$settings = Get-Content -Raw $path -Encoding UTF8
$settings = $settings -replace '`r`nThomas', '\nMike'
I tested different ways trying to find the "\nThomas" but nothing seems to work.

The pattern "`r`n..." will look for a literal carriage return and newline characters.
You aren't looking for any of those, you're looking for the verbatim escape sequence \n. To describe a backslash in a regex pattern, escape it with another backslash:
$settings -replace '\\nThomas', '\nMike'
You can also use [regex]::Escape() to escape any given verbatim string:
$settings -replace ([regex]::Escape('\nThomas')), '\nMike'

Related

Powershell for Linux: Combining commands with pipe sign doesn't work

Any way to concatenate commands in Powershell for Linux?
This is what I'm trying to run:
pwsh -Command Invoke-ScriptAnalyzer -Path . | ConvertTo-Json | Out-File -FilePath "/home/administrator/scripts/test.json"
So, run the Invoke-ScriptAnalyzer, convert the results to Json and save the result to test.json.
It doesn't recognize anything after the | sign:
./test.sh: line 1: ConvertTo-Json: command not found
./test.sh: line 1: Out-File: command not found
I need this to go in a bash script, hence the need to launch pwsh with the -Command option.
Any ideas?
Thanks
As written, your | symbols are interpreted by your Linux shell (such as bash), not by PowerShell.
There are two soutions:
Preferably, quote the entire -Command argument (a '...' string in a POSIX-compatible shell such as bash uses the string's content verbatim):
pwsh -Command 'Invoke-ScriptAnalyzer -Path . | ConvertTo-Json | Out-File -FilePath "/home/administrator/scripts/test.json"'
Alternatively, individually \-escape all Linux-shell metacharacters that you want to pass through verbatim, such as \| and \" in this case:
pwsh -Command Invoke-ScriptAnalyzer -Path . \| ConvertTo-Json \| Out-File -FilePath \"/home/administrator/scripts/test.json\"
Note: In this case, pwsh receives multiple arguments after -Command. However, PowerShell simply joins them before interpreting the result as PowerShell code.
This differs from the command-line processing of POSIX-compatible shells, which interpret the first post--c argument as an implicit, ad-hoc script, with additional arguments getting passed as verbatim arguments to that script, accessible as usual as $1, ...

Powershell newline in script argument not working

I have this little script i use to call it with differernt RegEx arguments for replacing text in files:
param ($file, $fnd, $rpl)
(Get-Content $file -Raw) -replace $fnd , $rpl | Set-Content $file
problem is if i pass it an argument containing a new line escape code `r`n like so:
powershell -File txt-replace.ps1 "file path" "RegEx_pattern" "line1`r`nline2"
will write on file:
line1`r`nline2
instead of:
line1
line2
BUT IF i define $rpl inside the script, with the exact argument content, it works:
$rpl = "line1`r`nline2"
writes:
line1
line2
Also works if i run it as a command in widows terminal:
powershell -command "(Get-Content file_path | Out-String ).Trim() | ForEach-Object {$_ -replace 'RegEx_pattern' , \"line1`r`nline2\"} | Set-Content file_path "
i debugged it further inside the script:
write-host $rpl
writes in terminal:
line1`r`nline2
BUT
$rpl= "line1`r`nline2"
write-host $rpl
writes in terminal:
line1
line2
What am i missing?
It is simplest to just use -Command parameter.
powershell -Command ".\txt-replace.ps1 \"file path\" \"RegEx_pattern\" \"line1`r`nline2\""
The backslash escapes are for the CMD shell. Since you want those quotes passed to PowerShell, we need to escape them first at the CMD shell layer. Otherwise, CMD will think they are surrounding strings for it to interpret.
When using -File the script arguments are passed literally after interpretation by the current shell. CMD doesn't know what the newline characters are so they just remain `r`n and then are passed literally as one of the string arguments.
When using -Command, the command string is treated as if it were entered at a PowerShell prompt.
See About_PowerShell.exe for more information.

Is there a way to escape a variable call in powershell?

I am trying to use powershell to generate a build.include script for visual studio. They both use ${variable} as a way of referencing variables.
I was wondering if there is a way to escape that in a string.
E.g
$string = #'
This is a `${string} I want to escape and {0} one I do not want to
'# -f $Var
I looked online and it said to escape $ you have to use the backtick. Doesn't seem to work for variables though?
Maybe use the following syntax:
$Var = 'one'
$string = #"
This is a `$Var I want to escape and {0} I do not want to
"# -f $Var
$string
Generates the following output:
This is a $Var I want to escape and one I do not want to
Another option is embedding the variable:
#"
This is a `${Var} I want to escape and $Var I do not want to
"#
Some remarks:
A here string is always between double quotes #""#
To escape a character use the backtick `
I figured it out. You must put double brackets.
Example:
$string = #'
This is a ${{string}} I want to escape and {0} one I do not want to
'# -f $Var

powershell escaping the escape character in a replace

Update - tried text without any back ticks still not replacing.
I have a file test.txt with these records:
name="BLUE_TBL_AC_EA_FREQ"` owner="BLUE_TBL_AC_EA_FREQ"
name="BLUE_TBL_AC_EA_FREQ" owner="RED_TBL_AC_EA_FREQ"
I would like to replace the string for the name attribute so I would use
name="BLUE_TBL_AC_EA_FREQ"
In the powershell script. This is what I did but the output file does not contain the replaced text, it is the same as the input.
Then I use a batch script that has this powershell command in the batch script
powershell -Command "(Get-Content "test.txt") | Foreach-Object {$_ -replace 'name="BLUE_TBL_AC_EA_FREQ"', 'name="BLUE_TBL_ACEAFREQ"'} | Set-Content "testo.txt""
The batch script does not replace the string that contains the string.
Am I doing something wrong, do I have to escape the double quotes for the string?
It is still not working for me.
End update
I am trying to use Powershell to replace some text in a file that makes use of the back tick.
In the file there is text such as
' name="BLUE_TBL_AC_EA_`FREQ"'
I would like to replace this text by
' name="BLUE_TBL_ACEAFREQ"'
The replace that I use in Powershell look like this
powershell -command "& {(Get-Content "file.txt") | Foreach-Object {$_ -replace ' name="BLUE_TBL_AC_EA_`FREQ"', ' name="BLUE_TBL_ACEAFREQ"'} | Set-Content "fileO.txt;}"
The ' name= is needed since there are multiple strings that contain the name="... string.
When I use this command nothing gets replaced. I have tried to escape the back tick by using a double back tick (``) and still nothing gets replaced.
I have searched and read many articles about Powershell and replacing text and the need for escaping characters. I thought I did what was needed but nothing gets replaced.
How do I replace the text that includes a back tick?
It looks like that when a replace is used in a batch script and the text contains either a back tick character or a double quote, then all the back ticks and the double quotes need to be escaped in the batch script.
The powershell command that was
powershell -Command "(Get-Content "test.txt") | Foreach-Object {$_ -replace 'name="BLUE_TBL_AC_EA_FREQ"', 'name="BLUE_TBL_ACEAFREQ"'} | Set-Content "testo.txt""
Becomes:
powershell -Command "(Get-Content "test.txt") | Foreach-Object {$_ -replace 'name=\"BLUE_TBL_AC_EA_FREQ\"', 'name=\"BLUE_TBL_ACEAFREQ\"'} | Set-Content "testo.txt""
If there is a back tick in the string then the back tick must be escaped as well using the reverse slash such as
\`
What a mess in a batch script.
Thanks for helping me figure this out.
I think your command have error that's why it is not changed. You missed the double quote after the txt, before the semicolon.
I tried this in my powershell and it is working.
(Get-Content "C:\test.txt") | Foreach-Object {$_ -replace ' name="BLUE_TBL_AC_EA_`FREQ"', ' name="BLUE_TBL_ACEAFREQ"'} | Set-Content "C:\test.txt"

Delete special characters from multiple csv files using batch file

I want to delete all the special characters in my csv file using a batch file. My csv file has one column of only keywords to be entered in google
For example
1.Ecommerce
2.dentist Melbourne cbd?
3.dentists Melbourne %
4.best dentist in Melbourne!
Sometimes I can have Aracbic/Chinese Characters as well and so on.
Here When I add these files to GoogleAdwords-Keyword Planner, it shows me an error, on ignoring error i get wrong no. of hits for keyword and to avoid error i need to remove all the special characters from my csv file.
I have Hundreds of csv files and want to save the updated(Without special characters) file to the existing file.
I tried
#echo off
set source_folder=C:\Users\Username\Documents\iMacros\Datasources\a
set target_folder=C:\Users\Username\Documents\iMacros\Datasources\keyfords-csv-file
if not exist %target_folder% mkdir %target_folder%
for /f %%A in ('dir /b %source_folder%\*.csv') do (
for /f "skip=1 tokens=1,2* delims=," %%B in (%source_folder%\%%A) do (
echo %%B>>%target_folder%\%%A
)
)
timeout /t 20
But ended up Deleting all the records from csv file.
Is there anyway by which i can either
1.Accept only Standard Characters which would be from A-Z, a-z, and 0-9.
2.Or Delete all the string where I can put special characters in that string. Like
string1="?%!##$^&*<>"
3.Or is there anyway by which i can mention in csv file to accept only Standard English Characters
Is there any way to achieve this using a batch file or any framework?
Thanks
I think this is much cleaner in Powershell.
$sourceFolder = "C:\Users\Username\Documents\iMacros\Datasources\a"
$targetFolder = "C:\Users\Username\Documents\iMacros\Datasources\keyfords-csv-file"
MkDir $targetFolder -ErrorAction Ignore
$fileList = Dir $sourceFolder -Filter *.csv
ForEach($file in $fileList)
{
$file | Get-Content | %{$_ -replace '[^\w\s,\"\.]',''} | Set-Content -Path "$targetFolder\$file"
}
I take every file from the source folder, get the contents, replace any character that is not wanted, and save it to another file. I use a little regex right in the middle '[^\w\s,\"\.]' with the replace command. The carrot ^ is a not match operator. So anything that does not match a word character \w, space character \s, a coma ,, double quote \", or a period \.
Someone may find a better regex for your needs, but I think you get the idea.
Technically you could have a series of:
set variable=%variable:"=%
set variable=%variable:(=%
set variable=%variable:)=%
set variable=%variable:&=%
set variable=%variable:%=%
And so on. I know this would be an annoyance to write all the special characters..
Seeing there would be less letters in the alphabet than "special characters" a findstr could be done on the file/folder name, if a letter from a-z is found true, write and move to the next character.
_Arescet

Resources