I have to replace the string xmlns="http://www.wnco.com/bookingevents/v2" with nothing in all files in a windows directory
Please help me in resolving this
You can do this using powershell wrapped up in a batch file. The following is an example:
#for %%I in (%1) do #call :FIXUP "%%~fI" %2
#goto EXIT
:FIXUP
#>tmp.ps1 echo.get-content %1 ^| foreach-object { $_ -replace %2,""} ^| set-content '%~1.fixed'
#set curdir=%~dp0
#set script=%curdir%tmp.ps1
#powershell -NoProfile -ExecutionPolicy Bypass -Command "& '%script%'"
#del >NUL /q %1 && #ren %1.fixed %1
#exit /b 0
:EXIT
The powershell script is created on the fly here and expects to see ASCII files. If you use unicode, check the "-Encoding Unicode" option for the powershell command.
So given a sample xml file as shown below we can use fixup.cmd *.xml "xmlns=""http://www.wnco.com/bookingevents/v2""" to apply this match expression to all the xml files in the current directory. I tested this using the following in some files:
<?xml version=1.0 encoding="UTF-8"?>
<a xmlns="http://www.wnco.com/bookingevents/v2">
<b>Something</b>
</a>
Running this:
C:\temp\demo>dir
27/02/2014 10:33 116 a.xml
27/02/2014 10:33 116 b.xml
27/02/2014 10:33 116 c 1.xml
27/02/2014 10:59 354 fixup.cmd
C:\temp\demo>fixup *.xml "xmlns=""http://www.wnco.com/bookingevents/v2"""
C:\temp\demo>type "c 1.xml"
<?xml version=1.0 encoding="UTF-8"?>
<a >
<b>Something</b>
</a>
The main issue to be careful with is the quoting to handle spaces in filenames.
Related
I want to read a .csv line by line, remove spaces, than echo the lines to another .csv as a "filtered" output. First my input:
test
test
t e st .
th isssss a te st
Now my parsing script (updated):
#echo off
SETLOCAL EnableDelayedExpansion
cls
del K:\Users\Ultron\test\test2.csv
echo CSRV>>K:\Users\Ultron\test\test2.csv
for /F "tokens=*" %%A in (K:\Users\Ultron\test\test.csv) do (
set "line=%%A"
echo %line%
echo %line% >>K:\Users\Ultron\test\test2.csv
)
notepad K:\Users\Ultron\test\test2.csv
Now notepad opens and reveals the hopefully expected result:
CSRV
ECHO Turned Off (OFF).
ECHO ist ausgeschaltet (OFF).
ECHO ist ausgeschaltet (OFF).
ECHO ist ausgeschaltet (OFF).
If I turn on echo I can see, that the lines are properly read, however it does not print them to the file. If the echo is on, the file contains the same information, only that it says, "ECHO is turned on (ON)."
It does not save the actual variable.
This is easily done using PowerShell. If you are on a supported Windows machine, PowerShell will be available. Note: this will remove -all- SPACE characters. It will not retain SPACE characters inside delimited fields of a CSV format file. That is the example in the question.
Get-Content -Path 'C:/src/t/test2.csv' |
ForEach-Object { $_ -replace ' ','' } |
Out-File -FilePath 'test3.csv' -Encoding utf8
If you must run from a cmd.exe console or .bat file script, this can be used.
powershell -NoLogo -NoProfile -Command ^
"Get-Content -Path 'test2.csv' |" ^
"ForEach-Object { $($_ -replace ' ','') } |" ^
"Out-File -FilePath 'test3.csv' -Encoding utf8"
The problem, it did not read and write correct was more than one detail.
Required for the fix:
I removed the tokens number
changed the file output. It has to use the !var! synthax (delayedexpansion)
remove a ")" which I did not see after many tries. How embarassing...
use a strange synthax like ('type "C:\path with spaces\stuff"'), so the script works with a path with a space - since this is the targeted usecase
The result looks just like:
#echo off
SETLOCAL EnableDelayedExpansion
cls
del "K:\Users\Ultron\test\te st\test2.csv"
echo CSRV>>"K:\Users\Ultron\test\te st\test2.csv"
for /F "tokens=*" %%A in ('type "K:\Users\Ultron\test\te st\test.csv"') do (
set "line=%%A"
set "line=!line: =!"
set "line=!line: =!"
(echo !line: =!)>>"K:\Users\Ultron\test\te st\test2.csv"
)
notepad "K:\Users\Ultron\test\3.7-12V_inductor_current\te st\test2.csv"
This results in the expected .csv:
test
test
test.
thisssssatest
I have a list of en.srt files in my folder. I need to convert them to .srt extension.
For example
Criminal Minds - 1x01 - Extreme Aggressor.en.srt to Criminal Minds - 1x01 - Extreme Aggressor.srt
Tried the below command and it didn't work,
ren *.en.srt *.srt
Renaming extension like ren *.srt *.srv works. (Changing all files' extensions in a folder with one command on Windows)
Would like to know if there is a workaround for this?
A simply though clumsy method is to rename the files twice – first remove .srt, then change .en to .srt (given that there are no other files *.en):
ren "*.en.srt" "*." & ren "*.en" "*.srt"
A more elegant solution is the one provided by user Mofi in his comment:
#for /F "eol=| delims=" %I in ('dir "*.en.srt" /B /A:-D 2^> nul') do #for %J in ("%~nI") do #ren "%~I" "%~nJ%~xI"
In a batch-file this code would look similar to this (note the necessarily doubled %-signs):
#echo off
rem // Loop through all matching files:
for /F "eol=| delims=" %%I in ('dir "*.en.srt" /B /A:-D 2^> nul') do (
rem /* There are `~`-modifiers for `for` meta-variables that allow to split file names:
rem `~n` returns the base name, so the (last) extension becomes removed;
rem `~x` returns the extension (including the leading `.`);
rem therefore, `%%~nI` is the original file name with `.srt` removed, hence
rem ending with `.en`, and `%%~xI` is the original extension `.srt`;
rem another loop is used to also split off `.en` from `%%~nI`: */
for %%J in ("%%~nI") do (
rem /* Now `%%~J` returned the same as `%%~nI`, but `%%~nJ` removes `.en`;
rem so finally, rename the file to `%%~nJ` plus the original extension `.srt`: */
ren "%%~I" "%%~nJ%%~xI"
)
)
Following the thorough thread How does the Windows RENAME command interpret wildcards? on Super User, I found out that there is a way using a single ren command:
ren "*.en.srt" "?????????????????????????????????????????.srt"
However, you need to make sure to have enough ?, namely as many as there are characters in longest matching file name without .en.srt; otherwise, file names become truncated. You can avoid truncation by replacing the same sequence of ? instead of *, so longer file names are not renamed at all:
ren "?????????????????????????????????????????.en.srt" "?????????????????????????????????????????.srt"
Anyway, this only works when the original file names do not contain any more . besides the two in .en.srt; otherwise, everything behind the first . becomes removed and (finally replaced by srt).
Not difficult in PowerShell to identify the files and replace the end of the filename with a regex. When you are confident that the files will be renamed correctly, remove the -WhatIf from the Move-Item command.
powershell -NoLogo -NoProfile -Command ^
"Get-ChildItem -File -Path '.' -Filter '*.en.srt' |" ^
"ForEach-Object {" ^
"Move-Item -Path $_.FullName -Destination $($_.FullName -replace 'en.srt$','srt') -WhatIf" ^
"}"
Of course, it would be easier if the command shell were PowerShell. BTW, this exact same code would work on Linux and Mac without change.
Get-ChildItem -File -Path '.' -Filter '*.en.srt' |
ForEach-Object {
Move-Item -Path $_.FullName -Destination $($_.FullName -replace 'en.srt$','srt') -WhatIf
}
I don't have a cmd at my disposition but I would guess that
ren *.en.srt *.tmp
ren *.tmp *.srt
works
The command I am executing is the following:
dir >> dir.txt
I would be interested in redirecting only certain lines to the txt, for example the last two lines. How can I do that? It occurs to me with findstr, but I don't know how.
A simple findstr match will isolate those two lines based upon them being the only two lines beginning with two spaces:
Dir | FindStr /BC:" " >> "dir.txt"
Assuming that you are under Windows, you can use the Win32 port of the Unix tail command from https://sourceforge.net/projects/tailforwin32/ and then issue the piped command:
dir | tail --lines=2
This shows the last 2 lines
Hope this helps
This can easily be done with PowerShell that you already have on your machine.
powershell -NoLogo -NoProfile -Command "& cmd.exe /C dir | Select-Object -Last 2 | Out-File -FilePath '.\dir.txt' -Encoding ascii -Append"
Alternatively...
powershell -NoLogo -NoProfile -Command "& cmd.exe /C dir | Select-Object -Last 2" >>dir.txt
Here is a simple batch file to get output the last two lines of standard output of command dir with language dependent information about
number of files in directory,
total number of bytes of the files in directory,
number of subdirectories in directory,
free space on partition in bytes.
dir excludes by default directories and files with hidden attribute set because of using implicit /A-H if dir option /A is not used at all.
Here is the batch file to get displayed the last two lines of output of dir executed without any parameters on current directory which of course can be different to directory containing the batch file.
#echo off
setlocal EnableExtensions EnableDelayedExpansion
set "SummaryFiles="
set "SummaryFolders="
for /F delims^=^ eol^= %%I in ('dir') do (
set "SummaryFiles=!SummaryFolders!"
set "SummaryFolders=%%I"
)
if defined SummaryFiles echo !SummaryFiles!
if defined SummaryFolders echo !SummaryFolders!
pause
endlocal
The output done by the two echo can be also redirected into a text file using for example
( if defined SummaryFiles echo !SummaryFiles!
if defined SummaryFolders echo !SummaryFolders!
) >DirectorySummary.txt
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
dir /?
echo /?
endlocal /?
for /?
if /?
pause /?
set /?
setlocal /?
I have several files like:
a.txt
a$.txt
a$b.txt
b.txt
b$.txt
b$c.txt
I would like to print file whose name does not contain '$' using Windows command line for file name pattern matching like regular expression:
for %%f in ([^$]+.txt) do type %%f
or
for %%f in ([a-zA-Z]+.txt) do type %%f
But it does not work. How can I do this using Windows command line? Thanks!
The for loop, like almost all cmd commands, does not support something like regular expressions. The only command that supports a tiny excerpt of those is findstr, which can be used together with dir to get the desired result:
#echo off
for /F "delims= eol=|" %%f in ('
dir /B /A:-D "*.txt" ^| findstr "^[^$][^$]*\.txt$"
') do (
>&2 echo/%%f
type "%%f"
)
This could even be simplified by replacing the portion findstr "^[^$][^$]*\.txt$" with find/V "$".
As 'Windows command line' includes powershell.exe as well as cmd.exe, I thought I'd offer a powershell based idea too.
Directly in powershell:
Get-Content -Path 'C:\Users\Xiagao\Desktop\*.txt' -Exclude '*$*.txt'
In cmd/batch-file, but leveraging powershell:
PowerShell -NoP "GC 'C:\Users\Xiagao\Desktop\*.txt' -Ex '*$*.txt'"
You would obviously modify the path to your source files location, (use .\*.txt for the current directory).
In a batch file, I'm opening a window with a specific name like this:
#echo off
start "my log" /D \logs\ /I powershell -nologo -noexit -command "$host.ui.RawUI.WindowTitle = 'My log'"; get-content logfile.log -wait
So the window title is "My log".
How do you run this command only if the window is not already open. Is there a bat file command to test for this? I'd rather not use a program or a powershell command, just a simple bat file cmd if possible.
Something like this:
#echo off
if EXISTS window("My log") goto skip
start "my log" /D \logs\ /I powershell -nologo -noexit -command "$host.ui.RawUI.WindowTitle = 'My log'"; get-content logfile.log -wait
:skip
#For /f "Delims=:" %A in ('tasklist /v /fi "WINDOWTITLE eq New Folder"') do #if %A==INFO echo Prog not running
More info on batch. Also see for /?.
& seperates commands on a line.
&& executes this command only if previous command's errorlevel is 0.
|| (not used above) executes this command only if previous command's errorlevel is NOT 0
> output to a file
>> append output to a file
< input from a file
| output of one command into the input of another command
^ escapes any of the above, including itself, if needed to be passed to a program
" parameters with spaces must be enclosed in quotes
+ used with copy to concatinate files. E.G. copy file1+file2 newfile
, used with copy to indicate missing parameters. This updates the files modified date. E.G. copy /b file1,,
%variablename% a inbuilt or user set environmental variable
!variablename! a user set environmental variable expanded at execution time, turned with SelLocal EnableDelayedExpansion command
%<number> (%1) the nth command line parameter passed to a batch file. %0 is the batchfile's name.
%* (%*) the entire command line.
%<a letter> or %%<a letter> (%A or %%A) the variable in a for loop. Single % sign at command prompt and double % sign in a batch file.
.
--
Always use tasklist, here is an example:
#echo off
for /f "tokens=*" %%a in ('tasklist /fi "WINDOWTITLE eq My log"') do if "%%a" == "INFO: No tasks are running which match the specified criteria." start "my log" /D \logs\ /I powershell -nologo -noexit -command "$host.ui.RawUI.WindowTitle = 'My log'"; get-content logfile.log -wait
That's right, you can do it on just 2 lines.